"""
Routes for PedimentoCustomsOffices CRUD operations
"""

from typing import Any, Dict, List

from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session

from ..dtos.pedimento_customs_offices import (
    PedimentoCustomsOfficesCreate,
    PedimentoCustomsOfficesResponse,
    PedimentoCustomsOfficesUpdate,
)
from ..services.pedimento_customs_offices import PedimentoCustomsOfficesService

router = APIRouter(prefix="/{pedimento_id}/customs-offices")


@router.get("/", response_model=List[PedimentoCustomsOfficesResponse])
async def list_customs_offices(
    pedimento_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Get all customs offices for a pedimento"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.view"]
    )

    offices = PedimentoCustomsOfficesService.get_by_pedimento_id(
        db, pedimento_id, tenant_id, company_id
    )
    return offices


@router.get("/{office_id}", response_model=PedimentoCustomsOfficesResponse)
async def get_customs_office(
    pedimento_id: int,
    office_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Get a specific customs office by ID"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.view"]
    )

    office = PedimentoCustomsOfficesService.get_by_id(
        db, office_id, pedimento_id, tenant_id, company_id
    )
    if not office:
        raise HTTPException(status_code=404, detail="Customs office not found")

    return office


@router.post("/", response_model=PedimentoCustomsOfficesResponse, status_code=201)
async def create_customs_office(
    pedimento_id: int,
    data: PedimentoCustomsOfficesCreate,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Create a new customs office"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.edit"]
    )

    # Ensure pedimento_id matches
    if data.pedimento_id != pedimento_id:
        raise HTTPException(status_code=400, detail="Pedimento ID mismatch")

    office = PedimentoCustomsOfficesService.create(db, data, tenant_id, company_id)
    return office


@router.put("/{office_id}", response_model=PedimentoCustomsOfficesResponse)
async def update_customs_office(
    pedimento_id: int,
    office_id: int,
    data: PedimentoCustomsOfficesUpdate,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Update a customs office"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.edit"]
    )

    office = PedimentoCustomsOfficesService.update(
        db, office_id, pedimento_id, tenant_id, company_id, data
    )
    if not office:
        raise HTTPException(status_code=404, detail="Customs office not found")

    return office


@router.delete("/{office_id}", status_code=204)
async def delete_customs_office(
    pedimento_id: int,
    office_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """Delete a customs office"""
    tenant_id = validate_access_to_resource(
        db, company_id, current_user, ["pedimentos_mgmt.edit"]
    )

    success = PedimentoCustomsOfficesService.delete(
        db, office_id, pedimento_id, tenant_id, company_id
    )
    if not success:
        raise HTTPException(status_code=404, detail="Customs office not found")

    return None
