from typing import List, Optional, Dict, Any

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

from core.database import get_core_db
from core.security import get_current_user, validate_access_to_resource
from .dtos import (
    ManifestAnexoCreateDTO,
    ManifestAnexoUpdateDTO,
    ManifestAnexoResponseDTO,
    ManifestAnexoListDTO,
)
from .service import ManifestAnexoService

router = APIRouter(prefix="/manifest-anexos")


@router.get("/", response_model=ManifestAnexoListDTO)
async def list_manifest_anexos(
    company_id: int = Query(..., description="Company ID"),
    consecutive: Optional[int] = Query(None, description="Filter by Consecutive"),
    search: Optional[str] = Query(None, description="Search term"),
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    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)
    filters = {"consecutive": consecutive, "search": search}
    items, total = ManifestAnexoService.get_all(
        db, tenant_id, company_id, skip=skip, limit=limit, filters=filters
    )
    return {
        "items": [ManifestAnexoResponseDTO.model_validate(item) for item in items],
        "total": total,
        "page": (skip // limit) + 1,
        "page_size": limit,
    }


@router.post("/", response_model=ManifestAnexoResponseDTO)
async def create_manifest_anexo(
    data: ManifestAnexoCreateDTO,
    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)
    return ManifestAnexoService.create(db, data, tenant_id, company_id)


@router.get("/{consecutive}/{line_number}", response_model=ManifestAnexoResponseDTO)
async def get_manifest_anexo(
    consecutive: int,
    line_number: 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)
    item = ManifestAnexoService.get_by_pk(db, consecutive, line_number, tenant_id, company_id)
    if not item:
        raise HTTPException(status_code=404, detail="Manifest Anexo not found")
    return item


@router.patch("/{consecutive}/{line_number}", response_model=ManifestAnexoResponseDTO)
async def update_manifest_anexo(
    consecutive: int,
    line_number: int,
    data: ManifestAnexoUpdateDTO,
    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)
    item = ManifestAnexoService.update(
        db, consecutive, line_number, tenant_id, company_id, data
    )
    if not item:
        raise HTTPException(status_code=404, detail="Manifest Anexo not found")
    return item


@router.delete("/{consecutive}/{line_number}", response_model=bool)
async def delete_manifest_anexo(
    consecutive: int,
    line_number: 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)
    success = ManifestAnexoService.delete(db, consecutive, line_number, tenant_id, company_id)
    if not success:
        raise HTTPException(status_code=404, detail="Manifest Anexo not found")
    return success
