"""Rotas Infra — códigos autorização purge (root / super_admin)."""

from __future__ import annotations

from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field

from app import auth, purge_auth_codes, vm112_domains
from app.permissions import can_manage_users

router = APIRouter(prefix="/api/v1/infra", tags=["infra-purge-auth"])


class PurgeAuthCodeCreate(BaseModel):
    domain: str = Field(..., min_length=3)
    root_password: str = Field(..., min_length=1)
    note: str = Field("", max_length=500)
    ttl_hours: int = Field(24, ge=1, le=168)


def _require_root_admin(user: auth.DeskUser = Depends(auth.get_current_user)) -> auth.DeskUser:
    if not can_manage_users(user.role):
        raise HTTPException(403, "Apenas super_admin (root) pode gerar códigos de purge")
    return user


@router.get("/purge-auth-codes")
def list_purge_auth_codes(
    active_only: bool = Query(True),
    limit: int = Query(50, ge=1, le=200),
    user: auth.DeskUser = Depends(_require_root_admin),
):
    conn = auth.db()
    try:
        purge_auth_codes.init_purge_auth_schema(conn)
        codes = purge_auth_codes.list_codes(conn, active_only=active_only, limit=limit)
        return {
            "codes": codes,
            "extra_auth_domains": sorted(vm112_domains.PURGE_EXTRA_AUTH_DOMAINS),
        }
    finally:
        conn.close()


@router.get("/purge-auth-domains")
def list_purge_auth_domains(
    user: auth.DeskUser = Depends(auth.get_current_user),
):
    return {
        "domains": sorted(vm112_domains.PURGE_EXTRA_AUTH_DOMAINS),
        "can_generate": can_manage_users(user.role),
    }


@router.post("/purge-auth-codes")
def create_purge_auth_code(
    body: PurgeAuthCodeCreate,
    user: auth.DeskUser = Depends(_require_root_admin),
):
    conn = auth.db()
    try:
        purge_auth_codes.init_purge_auth_schema(conn)
        result = purge_auth_codes.create_code(
            conn,
            body.domain,
            body.root_password,
            user.username,
            body.note,
            ttl_hours=body.ttl_hours,
        )
        return result
    except ValueError as exc:
        raise HTTPException(400, str(exc)) from exc
    finally:
        conn.close()
