"""Endpoint independiente para validar PIN de supervisor."""
from fastapi import APIRouter, HTTPException
from schemas import ValidarPinRequest, ValidarPinResponse
from services.supervisor_service import validar_pin_supervisor

router = APIRouter(prefix="/api/supervisor", tags=["Supervisor"])


@router.post("/validar-pin", response_model=ValidarPinResponse)
async def validar_pin(req: ValidarPinRequest):
    """Valida PIN de supervisor contra el cloud. Requiere motivo obligatorio (excepto accesos por permiso)."""
    acciones_sin_motivo = {'config_impresora'}
    if req.accion not in acciones_sin_motivo:
        if not req.motivo or not req.motivo.strip():
            raise HTTPException(status_code=400, detail="Motivo/justificacion es obligatorio")

    try:
        result = await validar_pin_supervisor(req.pin, req.accion, req.solicitante, req.motivo)
    except Exception:
        raise HTTPException(status_code=503, detail="No se pudo conectar al servidor cloud para validar PIN")

    if result.get('status') != 'ok':
        raise HTTPException(status_code=403, detail=result.get('message', 'PIN de supervisor invalido'))

    return ValidarPinResponse(
        status="ok",
        supervisor=result.get('supervisor'),
        supervisor_id=result.get('supervisor_id'),
        permiso=result.get('permiso', 'completo'),
    )
