"""admin 账号管理(仅 super_admin):列表 / 创建 / 改角色启停重置密码。均写审计。"""
from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Request

from app.admin.audit import write_audit
from app.admin.deps import AdminDb, CurrentAdmin, get_client_ip, require_role
from app.admin.repositories import admin_user as admin_repo
from app.admin.schemas.admin import AdminCreateRequest, AdminUpdateRequest
from app.admin.schemas.auth import AdminOut
from app.core.security import hash_password

router = APIRouter(
    prefix="/admin/api/admins",
    tags=["admin-accounts"],
    dependencies=[Depends(require_role())],  # require_role() 无参 = 仅 super_admin 通过
)


def _active_super_count(db: AdminDb) -> int:
    return sum(
        1 for a in admin_repo.list_admins(db) if a.role == "super_admin" and a.status == "active"
    )


@router.get("", response_model=list[AdminOut], summary="管理员列表")
def list_admins(db: AdminDb) -> list[AdminOut]:
    return [AdminOut.model_validate(a) for a in admin_repo.list_admins(db)]


@router.post("", response_model=AdminOut, summary="创建管理员")
def create_admin(
    body: AdminCreateRequest, request: Request, admin: CurrentAdmin, db: AdminDb
) -> AdminOut:
    if admin_repo.get_by_username(db, body.username) is not None:
        raise HTTPException(status_code=409, detail="用户名已存在")
    new = admin_repo.create_admin(
        db, username=body.username, password=body.password, role=body.role
    )
    write_audit(
        db, admin, action="admin.create", target_type="admin", target_id=new.id,
        detail={"username": new.username, "role": new.role}, ip=get_client_ip(request), commit=True,
    )
    return AdminOut.model_validate(new)


@router.patch("/{admin_id}", response_model=AdminOut, summary="改角色/启停/重置密码")
def update_admin(
    admin_id: int, body: AdminUpdateRequest, request: Request, admin: CurrentAdmin, db: AdminDb
) -> AdminOut:
    target = admin_repo.get_by_id(db, admin_id)
    if target is None:
        raise HTTPException(status_code=404, detail="管理员不存在")
    if admin_id == admin.id and body.status == "disabled":
        raise HTTPException(status_code=400, detail="不能禁用自己")

    # 防自锁:降级 / 禁用某个 super_admin 前,确认操作后仍至少剩 1 个 active super_admin,
    # 否则会进入「零可用超管」死局——本路由仅 super 可进,只能改库恢复。
    demotes_super = (
        target.role == "super_admin"
        and target.status == "active"
        and (
            (body.role is not None and body.role != "super_admin")
            or body.status == "disabled"
        )
    )
    if demotes_super and _active_super_count(db) <= 1:
        raise HTTPException(status_code=400, detail="不能降级/禁用最后一个超级管理员")

    changes: dict = {}
    if body.role is not None and body.role != target.role:
        changes["role"] = {"before": target.role, "after": body.role}
        target.role = body.role
    if body.status is not None and body.status != target.status:
        changes["status"] = {"before": target.status, "after": body.status}
        target.status = body.status
    if body.password is not None:
        changes["password"] = "reset"
        target.password_hash = hash_password(body.password)
    if not changes:
        raise HTTPException(status_code=400, detail="无任何变更字段")
    db.commit()
    db.refresh(target)
    write_audit(
        db, admin, action="admin.update", target_type="admin", target_id=admin_id,
        detail=changes, ip=get_client_ip(request), commit=True,
    )
    return AdminOut.model_validate(target)
