"""API admin — domínios orquestrados (Desk Spec 017)."""

from fastapi import APIRouter, BackgroundTasks, Depends, Header, HTTPException, Query

from app.config import settings
from app.services import domain_orchestration, purge_jobs

router = APIRouter(prefix="/admin/domains", tags=["admin-domains"])


def require_api_key(x_api_key: str | None = Header(default=None, alias="X-Api-Key")):
    if x_api_key != settings.admin_api_key:
        raise HTTPException(401, "API key inválida")
    return True


@router.get("/purge-jobs/{job_id}", dependencies=[Depends(require_api_key)])
def get_purge_job(job_id: str):
    job = purge_jobs.get_job(job_id)
    if not job:
        raise HTTPException(404, "Job de purge não encontrado")
    return job


@router.get("", dependencies=[Depends(require_api_key)])
def list_domains(q: str = Query(default="")):
    return domain_orchestration.list_orchestrated_domains_meta(q)


@router.get("/{domain}", dependencies=[Depends(require_api_key)])
def domain_detail(domain: str):
    try:
        return domain_orchestration.get_domain_detail(domain.lower().strip())
    except ValueError as e:
        raise HTTPException(404, str(e)) from e


@router.post("/{domain}/purge", dependencies=[Depends(require_api_key)])
def purge_domain(domain: str, background_tasks: BackgroundTasks, sync: bool = Query(default=False)):
    """Inicia purge assíncrono (Fase 3). Desk faz poll em purge-jobs/{job_id}."""
    domain = domain.lower().strip()
    try:
        domain_orchestration.assert_purge_allowed(domain)
        if sync:
            result = domain_orchestration.purge_domain(domain)
            return {"ok": True, "steps": result.get("steps", []), "result": result}
        meta = purge_jobs.create_job(domain)
        background_tasks.add_task(domain_orchestration.run_purge_job, meta["job_id"])
        return {"ok": True, **meta}
    except ValueError as e:
        raise HTTPException(400, str(e)) from e
    except Exception as e:
        raise HTTPException(500, str(e)) from e
