"""add more system settings

Revision ID: 044_more_system_settings
Revises: 043_member_commission
Create Date: 2026-06-18
"""
import json

import sqlalchemy as sa
from alembic import op

from app.config import settings as app_settings


revision = "044_more_system_settings"
down_revision = "043_member_commission"
branch_labels = None
depends_on = None


DEFAULT_SETTINGS = [
    (
        "platform.site_name",
        "清云互联",
        "站点名称",
        "用于后台展示、支付订单名称和部分通知文案。",
    ),
    (
        "platform.registration_enabled",
        True,
        "开放新用户注册",
        "关闭后新用户无法获取注册验证码或完成注册，已有用户登录不受影响。",
    ),
    (
        "platform.frontend_url",
        app_settings.FRONTEND_URL,
        "前台访问地址",
        "用于邮件通知、跳转链接等场景。",
    ),
    (
        "platform.promotion_base_url",
        app_settings.FRONTEND_URL,
        "推广链接基础地址",
        "推广码生成注册链接时使用的前台地址。",
    ),
    (
        "finance.recharge_min_cents",
        max(1, int(app_settings.RECHARGE_MIN_YUAN * 100)),
        "最低充值金额",
        "用户单笔充值的最低金额。",
    ),
    (
        "finance.recharge_max_cents",
        max(1, int(app_settings.RECHARGE_MAX_YUAN * 100)),
        "最高充值金额",
        "用户单笔充值的最高金额。",
    ),
    (
        "finance.pending_payment_ttl_minutes",
        15,
        "待支付保留时间",
        "充值订单创建后，前台保留待支付入口的时间。",
    ),
    (
        "finance.recharge_enabled",
        True,
        "开放余额充值",
        "关闭后用户不能创建新的充值订单，已创建订单和支付回调仍会继续处理。",
    ),
    (
        "promotion.invite_code_edit_enabled",
        True,
        "允许自定义推广码",
        "关闭后用户不能修改自己的推广码，已有推广码和绑定关系继续有效。",
    ),
    (
        "promotion.settlement_check_interval_minutes",
        5,
        "奖励释放扫描频率",
        "后台扫描冻结代理收益和普通推广奖励的频率。",
    ),
]


def upgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())
    if "system_settings" not in tables:
        return

    for key, value, label, description in DEFAULT_SETTINGS:
        existing = bind.execute(
            sa.text("SELECT id FROM system_settings WHERE `key` = :key LIMIT 1"),
            {"key": key},
        ).first()
        if existing:
            continue
        bind.execute(
            sa.text(
                """
                INSERT INTO system_settings (`key`, `value`, label, description, created_at, updated_at)
                VALUES (:key, :value, :label, :description, NOW(), NOW())
                """
            ),
            {
                "key": key,
                "value": json.dumps(value, ensure_ascii=False),
                "label": label,
                "description": description,
            },
        )


def downgrade() -> None:
    bind = op.get_bind()
    tables = set(sa.inspect(bind).get_table_names())
    if "system_settings" not in tables:
        return
    for key, *_ in DEFAULT_SETTINGS:
        bind.execute(
            sa.text("DELETE FROM system_settings WHERE `key` = :key"),
            {"key": key},
        )
