"""平台角色管理 API：仅 PLATFORM_OWNER 可访问"""

import uuid

from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.audit import audit_log
from app.core.permissions import PlatformRole, require_platform_owner
from app.db import get_db
from app.models.user import User


class SetPlatformRoleRequest(BaseModel):
    role: str


router = APIRouter(dependencies=[Depends(require_platform_owner)])


@router.get("/platform-roles", response_model=dict, summary="平台角色成员列表")
async def list_platform_members(
    db: AsyncSession = Depends(get_db),
    page: int = Query(1, ge=1),
    page_size: int = Query(50, ge=1, le=200),
):
    """列出所有有平台角色的用户"""
    from sqlalchemy import func as sfunc
    qs = select(User).where(User.platform_role.isnot(None))
    total = (await db.execute(select(sfunc.count()).select_from(qs.subquery()))).scalar() or 0
    result = await db.execute(
        qs.order_by(User.platform_role, User.display_name)
        .offset((page - 1) * page_size).limit(page_size)
    )
    users = result.scalars().all()
    return {
        "items": [
            {
                "id": str(u.id), "email": u.email, "display_name": u.display_name,
                "platform_role": u.platform_role,
                "last_login_at": u.last_login_at.isoformat() if u.last_login_at else None,
                "created_at": u.created_at.isoformat() if u.created_at else None,
            }
            for u in users
        ],
        "total": total,
    }


@router.put("/platform-roles/{uid}", summary="设置用户平台角色")
async def set_platform_role(
    uid: str,
    req: SetPlatformRoleRequest,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_platform_owner),
):
    """设置/变更用户的平台角色。PLATFORM_OWNER 专属。

    - 禁止操作者对自己操作
    - 禁止将目标角色设置为 OWNER（防止被删除所有权）
    """
    try:
        target_uuid = uuid.UUID(uid)
        operator_uuid = uuid.UUID(current_user["sub"])
    except ValueError:
        raise HTTPException(400, "Invalid UUID")

    if target_uuid == operator_uuid:
        raise HTTPException(400, "不能修改自己的角色")

    # 验证角色值
    target_role = req.role
    try:
        PlatformRole(target_role)
    except ValueError:
        raise HTTPException(400, f"无效的平台角色: {target_role}")

    # 查目标用户
    user = (await db.execute(select(User).where(User.id == target_uuid))).scalar()
    if not user:
        raise HTTPException(404, "用户不存在")

    old_role = user.platform_role
    if old_role == target_role:
        raise HTTPException(400, "目标用户已是此角色")

    user.platform_role = target_role
    await db.commit()

    await audit_log(
        db, action="platform_role_change",
        actor_id=operator_uuid,
        target_type="user", target_id=uid,
        detail=f"platform_role: {old_role} → {target_role}",
    )

    return {"status": "updated", "from": old_role, "to": target_role}


@router.delete("/platform-roles/{uid}", summary="移除用户平台角色")
async def remove_platform_role(
    uid: str,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_platform_owner),
):
    """移除用户的平台角色（降为普通用户）"""
    try:
        target_uuid = uuid.UUID(uid)
        operator_uuid = uuid.UUID(current_user["sub"])
    except ValueError:
        raise HTTPException(400, "Invalid UUID")

    if target_uuid == operator_uuid:
        raise HTTPException(400, "不能移除自己的平台角色")

    user = (await db.execute(select(User).where(User.id == target_uuid))).scalar()
    if not user:
        raise HTTPException(404, "用户不存在")
    if not user.platform_role:
        raise HTTPException(400, "该用户没有平台角色")

    old_role = user.platform_role
    user.platform_role = None
    await db.commit()

    await audit_log(
        db, action="platform_role_remove",
        actor_id=operator_uuid,
        target_type="user", target_id=uid,
        detail=f"platform_role: {old_role} → None",
    )

    return {"status": "removed", "from": old_role}
