"""Superadmin：管理各租户的小程序渠道配置"""
from typing import Optional, List
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_superadmin_user
from app.core.models.user import User
from app.core.models.tenant_channel import TenantChannel

router = APIRouter(prefix="/superadmin/tenant-channels", tags=["Superadmin渠道管理"])


class ChannelIn(BaseModel):
    tenant_id: int
    channel: str = "wechat_miniapp"
    appid: str
    app_name: Optional[str] = None
    status: str = "active"
    public_config: Optional[dict] = None
    secret_config: Optional[dict] = None


class ChannelOut(BaseModel):
    id: int
    tenant_id: int
    channel: str
    appid: str
    app_name: Optional[str]
    status: str
    public_config: dict

    class Config:
        from_attributes = True


@router.get("", response_model=List[ChannelOut])
async def list_channels(
    db: AsyncSession = Depends(get_db),
    _: User = Depends(get_superadmin_user),
):
    r = await db.execute(select(TenantChannel).order_by(TenantChannel.id))
    channels = r.scalars().all()
    return [
        ChannelOut(
            id=ch.id, tenant_id=ch.tenant_id, channel=ch.channel,
            appid=ch.appid, app_name=ch.app_name, status=ch.status,
            public_config=ch.get_public_config(),
        )
        for ch in channels
    ]


@router.post("", response_model=ChannelOut, status_code=201)
async def create_channel(
    body: ChannelIn,
    db: AsyncSession = Depends(get_db),
    _: User = Depends(get_superadmin_user),
):
    config_json = {
        "public": body.public_config or {},
        "secret": body.secret_config or {},
    }
    ch = TenantChannel(
        tenant_id=body.tenant_id,
        channel=body.channel,
        appid=body.appid,
        app_name=body.app_name,
        status=body.status,
        config_json=config_json,
    )
    db.add(ch)
    await db.commit()
    await db.refresh(ch)
    return ChannelOut(
        id=ch.id, tenant_id=ch.tenant_id, channel=ch.channel,
        appid=ch.appid, app_name=ch.app_name, status=ch.status,
        public_config=ch.get_public_config(),
    )


@router.patch("/{channel_id}", response_model=ChannelOut)
async def update_channel(
    channel_id: int,
    body: ChannelIn,
    db: AsyncSession = Depends(get_db),
    _: User = Depends(get_superadmin_user),
):
    r = await db.execute(select(TenantChannel).where(TenantChannel.id == channel_id))
    ch = r.scalar_one_or_none()
    if not ch:
        raise HTTPException(status_code=404, detail="渠道不存在")

    existing_cfg = ch.config_json or {}
    old_appid = ch.appid
    ch.channel = body.channel
    ch.appid = body.appid
    ch.app_name = body.app_name
    ch.status = body.status
    ch.config_json = {
        "public": body.public_config if body.public_config is not None else existing_cfg.get("public", {}),
        "secret": body.secret_config if body.secret_config is not None else existing_cfg.get("secret", {}),
    }
    await db.commit()

    from app.core.cache import cache_delete
    await cache_delete(f"mp:appid:{old_appid}")
    if body.appid != old_appid:
        await cache_delete(f"mp:appid:{body.appid}")

    return ChannelOut(
        id=ch.id, tenant_id=ch.tenant_id, channel=ch.channel,
        appid=ch.appid, app_name=ch.app_name, status=ch.status,
        public_config=ch.get_public_config(),
    )


@router.delete("/{channel_id}", status_code=204)
async def delete_channel(
    channel_id: int,
    db: AsyncSession = Depends(get_db),
    _: User = Depends(get_superadmin_user),
):
    r = await db.execute(select(TenantChannel).where(TenantChannel.id == channel_id))
    ch = r.scalar_one_or_none()
    if not ch:
        raise HTTPException(status_code=404, detail="渠道不存在")
    from app.core.cache import cache_delete
    await cache_delete(f"mp:appid:{ch.appid}")
    await db.delete(ch)
    await db.commit()
