from typing import Dict, Any
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

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

from api.v1.common.tenant_crud_routes import TenantCRUDRoutes
from . import dto, services
from ..layouts_csv.customs_brokers.routes import router as imports_router

router = APIRouter()

# CSV import (mismo flujo que a76.imports: upload → scan → commit)
router.include_router(imports_router, prefix="/customs-brokers/imports", tags=["customs_brokers / csv_import"])

customs_broker_crud = TenantCRUDRoutes(
    service=services.CustomsBrokerService,
    create_schema=dto.CustomsBrokerCreateDTO,
    update_schema=dto.CustomsBrokerUpdateDTO,
    response_schema=dto.CustomsBrokerResponseDTO,
    prefix="/customs-brokers", 
    tags=[],
    resource_name="Customs Broker",
    id_name="broker_key",
    id_type=str,
    enable_list=True,
)

router.include_router(customs_broker_crud.router)


@router.patch(
    "/customs-brokers/{broker_key}", 
    response_model=dto.CustomsBrokerResponseDTO,
)
def update_customs_broker(
    broker_key: str,
    broker_data: dto.CustomsBrokerUpdateDTO,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """
    Actualización parcial (PATCH).
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    
    broker = services.CustomsBrokerService.get_by_id(db, broker_key, tenant_id, company_id)
    if not broker:
        raise HTTPException(status_code=404, detail="Customs Broker not found")

    updated_broker = services.CustomsBrokerService.update(
        db=db,
        broker_key=broker_key,
        tenant_id=tenant_id,
        broker_data=broker_data,  
        company_id=company_id     
    )
    
    if not updated_broker:
        raise HTTPException(status_code=400, detail="Error updating Customs Broker")
        
    return updated_broker


@router.put(
    "/customs-broker-vu/{broker_key}", 
    response_model=dto.CustomsBrokerVUResponseDTO,
)
def update_customs_broker_vu(
    broker_key: str,
    vu_data: dto.CustomsBrokerVUCreateDTO,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    
    broker = services.CustomsBrokerService.get_by_id(db, broker_key, tenant_id, company_id)
    if not broker:
        raise HTTPException(status_code=404, detail="Customs Broker not found")
    
    updated_vu = services.CustomsBrokerVUService.update_vu(db, broker_key, vu_data, tenant_id, company_id)
    if not updated_vu:
        raise HTTPException(status_code=404, detail="Customs Broker VU not found")
    return updated_vu


@router.put(
    "/customs-broker-personnel/{broker_key}/{line}",
    response_model=dto.CustomsBrokerPersonnelDTO,
)
def update_customs_broker_personnel(
    broker_key: str,
    line: int,
    personnel_data: dto.CustomsBrokerPersonnelDTO,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    
    broker = services.CustomsBrokerService.get_by_id(db, broker_key, tenant_id, company_id)
    if not broker:
        raise HTTPException(status_code=404, detail="Customs Broker not found")
    
    updated_personnel = services.CustomsBrokerPersonnelService.update_personnel(
        db, broker_key, line, personnel_data, tenant_id, company_id
    )
    if not updated_personnel:
        raise HTTPException(
            status_code=404, detail="Customs Broker Personnel not found"
        )
    return updated_personnel