"""Endpoints de catálogos de referencia y participantes del proceso (R-T-01, R-T-10)."""

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from core.database import get_core_db
from core.security import get_current_user

from ..accounts.models import Account
from ..suppliers.models import Supplier
from .data import INCOTERMS, PARTICIPANT_ROLES

router = APIRouter()


@router.get("/catalogs/incoterms")
def list_incoterms(
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
):
    """Catálogo de Incoterms 2020 (R-T-10)."""
    return INCOTERMS


@router.get("/catalogs/participant-roles")
def list_participant_roles(
    company_id: int = Query(..., description="Company ID"),
    current_user: dict = Depends(get_current_user),
):
    """Catálogo de roles/actores del proceso, incluida la autoridad aduanera (R-T-01)."""
    return PARTICIPANT_ROLES


@router.get("/participants")
def list_participants(
    company_id: int = Query(..., description="Company ID"),
    role: str | None = Query(None, description="Filtra por rol/clasificación"),
    current_user: dict = Depends(get_current_user),
    db: Session = Depends(get_core_db),
):
    """Vista unificada de participantes del proceso: clientes/prospectos (cuentas) y
    actores externos (proveedores por clasificación), en un solo catálogo (R-T-01)."""
    tenant_id = current_user["tenant_id"]
    result: list[dict] = []

    accounts = (
        db.query(Account)
        .filter(
            Account.tenant_id == tenant_id,
            Account.company_id == company_id,
            Account.deleted_at.is_(None),
        )
        .all()
    )
    for acc in accounts:
        acc_role = getattr(acc, "record_type", None) or "cliente"
        if role and role not in (acc_role, "exportador", "importador"):
            # Las cuentas representan exportador/importador/cliente; sólo se omiten
            # cuando el filtro pide explícitamente un rol de proveedor.
            if role not in ("exportador", "importador", "cliente", "prospecto"):
                continue
        result.append({
            "id": acc.id,
            "source": "account",
            "name": acc.name,
            "role": acc_role,
            "roles": [acc_role],
        })

    suppliers = (
        db.query(Supplier)
        .filter(
            Supplier.tenant_id == tenant_id,
            Supplier.company_id == company_id,
            Supplier.deleted_at.is_(None),
        )
        .all()
    )
    for sup in suppliers:
        classifications = sup.classifications or []
        if role and role not in classifications:
            continue
        result.append({
            "id": sup.id,
            "source": "supplier",
            "name": sup.name,
            "role": classifications[0] if classifications else "proveedor",
            "roles": classifications,
        })

    return result
