"""admin 华为审核开关:控制新手引导页(快速设置)在华为 ROM 客户端能否被用户关闭。

存在 app_config 表的 huawei_review dict(见 repositories/app_config.get_huawei_review/set_huawei_review)。
客户端经 /api/v1/platform/huawei-review 拉取(且只有华为 ROM 机型会去拉)。权限 operator/tech + 审计。
"""
from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session

from app.admin.audit import write_audit
from app.admin.deps import AdminDb, get_client_ip, get_current_admin, require_role
from app.admin.schemas.huawei_review import HuaweiReviewOut, HuaweiReviewUpdate
from app.models.admin import AdminUser
from app.models.app_config import AppConfig
from app.repositories import app_config

router = APIRouter(
    prefix="/admin/api/huawei-review",
    tags=["admin-huawei-review"],
    dependencies=[Depends(get_current_admin)],
)


def _out(db: Session) -> HuaweiReviewOut:
    row = db.get(AppConfig, app_config.HUAWEI_REVIEW_KEY)
    return HuaweiReviewOut(
        mode=app_config.get_huawei_review(db)["mode"],
        updated_at=row.updated_at.isoformat() if row is not None else None,
    )


@router.get("", response_model=HuaweiReviewOut, summary="华为审核开关当前状态")
def get_huawei_review(db: AdminDb) -> HuaweiReviewOut:
    return _out(db)


@router.patch("", response_model=HuaweiReviewOut, summary="切换华为审核开关(带审计)")
def update_huawei_review(
    body: HuaweiReviewUpdate,
    request: Request,
    admin: Annotated[AdminUser, Depends(require_role("operator", "tech"))],
    db: AdminDb,
) -> HuaweiReviewOut:
    before = app_config.get_huawei_review(db)["mode"]
    try:
        app_config.set_huawei_review(db, body.mode, admin_id=admin.id, commit=False)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e)) from e
    write_audit(
        db, admin, action="huawei_review.set", target_type="huawei_review",
        target_id=app_config.HUAWEI_REVIEW_KEY,
        detail={"before": before, "after": body.mode}, ip=get_client_ip(request), commit=False,
    )
    db.commit()
    return _out(db)
