"""
Rutas para gestión de DODA (Documentos de Operación de Aduana)
"""

from typing import List

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

from core.database import get_core_db
from api.v1.common.tenant_crud_routes import TenantCRUDRoutes
from .dto import (
    DodaCreateDTO,
    DodaResponseDTO,
    DodaUpdateDTO,
    DodaDetailResponseDTO,
    DodaContainerCreateDTO,
    DodaContainerResponseDTO,
    DodaContainerUpdateDTO,
    DodaAmericanPedimentoCreateDTO,
    DodaAmericanPedimentoResponseDTO,
    DodaAmericanPedimentoUpdateDTO,
    DodaPedimentoCreateDTO,
    DodaPedimentoResponseDTO,
    DodaPedimentoUpdateDTO,
)
from .models import Doda
from .service import DodaService
from core.security import get_current_user, validate_access_to_resource

# Create CRUD router
crud_router = TenantCRUDRoutes(
    service=DodaService,
    create_schema=DodaCreateDTO,
    update_schema=DodaUpdateDTO,
    response_schema=DodaResponseDTO,
    prefix="/doda",
    tags=["doda"],
    resource_name="DODA",
    id_name="doda_id",
    enable_list=True,
    enable_filters=True,
).router

router = crud_router

# ============ CUSTOM ENDPOINTS ============


@router.get(
    "/{doda_id}/detail",
    response_model=DodaDetailResponseDTO,
    summary="Get DODA by ID with all details",
)
async def get_doda_detail(
    doda_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    doda = DodaService.get_by_id(db, doda_id, tenant_id, company_id)
    if not doda:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="DODA not found",
        )
    return DodaDetailResponseDTO.model_validate(doda)


# ============ CONTAINERS ENDPOINTS ============
@router.get(
    "/{doda_id}/containers",
    response_model=List[DodaContainerResponseDTO],
    summary="Get containers for DODA",
)
async def get_doda_containers(
    doda_id: int,
    db: Session = Depends(get_core_db),
):
    """Get all containers for a specific DODA"""
    containers = DodaService.get_containers(db, doda_id)
    return [DodaContainerResponseDTO.model_validate(c) for c in containers]


@router.post(
    "/{doda_id}/containers",
    response_model=DodaContainerResponseDTO,
    status_code=status.HTTP_201_CREATED,
    summary="Add container to DODA",
)
async def add_container(
    doda_id: int,
    container_data: DodaContainerCreateDTO,
    db: Session = Depends(get_core_db),
):
    """Add a new container to a DODA"""
    container = DodaService.add_container(db, doda_id, container_data)
    if not container:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="DODA not found",
        )
    return DodaContainerResponseDTO.model_validate(container)


@router.put(
    "/{doda_id}/containers/{container_line}",
    response_model=DodaContainerResponseDTO,
    summary="Update container",
)
async def update_container(
    doda_id: int,
    container_line: int,
    container_data: DodaContainerUpdateDTO,
    db: Session = Depends(get_core_db),
):
    """Update a container"""
    container = DodaService.update_container(
        db, doda_id, container_line, container_data
    )
    if not container:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Container not found",
        )
    return DodaContainerResponseDTO.model_validate(container)


# ============ AMERICAN PEDIMENTOS ENDPOINTS ============
@router.get(
    "/{doda_id}/american-pedimentos",
    response_model=List[DodaAmericanPedimentoResponseDTO],
    summary="Get American pedimentos for DODA",
)
async def get_american_pedimentos(
    doda_id: int,
    db: Session = Depends(get_core_db),
):
    """Get all American pedimentos for a specific DODA"""
    pedimentos = DodaService.get_american_pedimentos(db, doda_id)
    return [DodaAmericanPedimentoResponseDTO.model_validate(p) for p in pedimentos]


@router.post(
    "/{doda_id}/american-pedimentos",
    response_model=DodaAmericanPedimentoResponseDTO,
    status_code=status.HTTP_201_CREATED,
    summary="Add American pedimento to DODA",
)
async def add_american_pedimento(
    doda_id: int,
    pedimento_data: DodaAmericanPedimentoCreateDTO,
    db: Session = Depends(get_core_db),
):
    """Add a new American pedimento to a DODA"""
    pedimento = DodaService.add_american_pedimento(db, doda_id, pedimento_data)
    if not pedimento:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="DODA not found",
        )
    return DodaAmericanPedimentoResponseDTO.model_validate(pedimento)


# ============ PEDIMENTOS ENDPOINTS ============
@router.get(
    "/{doda_id}/pedimentos",
    response_model=List[DodaPedimentoResponseDTO],
    summary="Get pedimentos for DODA",
)
async def get_doda_pedimentos(
    doda_id: int,
    db: Session = Depends(get_core_db),
):
    """Get all pedimentos for a specific DODA"""
    pedimentos = DodaService.get_pedimentos(db, doda_id)
    return [DodaPedimentoResponseDTO.model_validate(p) for p in pedimentos]


@router.post(
    "/{doda_id}/pedimentos",
    response_model=DodaPedimentoResponseDTO,
    status_code=status.HTTP_201_CREATED,
    summary="Add pedimento to DODA",
)
async def add_pedimento(
    doda_id: int,
    pedimento_data: DodaPedimentoCreateDTO,
    db: Session = Depends(get_core_db),
):
    """Add a new pedimento to a DODA"""
    pedimento = DodaService.add_pedimento(db, doda_id, pedimento_data)
    if not pedimento:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="DODA not found",
        )
    return DodaPedimentoResponseDTO.model_validate(pedimento)
