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 (
    ManifestDriverCreateDTO,
    ManifestDriverUpdateDTO,
    ManifestDriverResponseDTO,
    ManifestDriverListDTO,
)
from .service import ManifestDriverService

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


@router.get("/", response_model=ManifestDriverListDTO)
async def list_manifest_drivers(
    company_id: int = Query(..., description="Company ID"),
    manifest_number: Optional[str] = Query(None, description="Filter by Manifest Number"),
    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 = {"manifest_number": manifest_number, "search": search}
    items, total = ManifestDriverService.get_all(
        db, tenant_id, company_id, skip=skip, limit=limit, filters=filters
    )
    return {
        "items": [ManifestDriverResponseDTO.model_validate(item) for item in items],
        "total": total,
        "page": (skip // limit) + 1,
        "page_size": limit,
    }


@router.post("/", response_model=ManifestDriverResponseDTO)
async def create_manifest_driver(
    data: ManifestDriverCreateDTO,
    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 ManifestDriverService.create(db, data, tenant_id, company_id)


@router.get("/{manifest_number}/{driver_name}", response_model=ManifestDriverResponseDTO)
async def get_manifest_driver(
    manifest_number: str,
    driver_name: str,
    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 = ManifestDriverService.get_by_pk(db, manifest_number, driver_name, tenant_id, company_id)
    if not item:
        raise HTTPException(status_code=404, detail="Manifest Driver not found")
    return item


@router.patch("/{manifest_number}/{driver_name}", response_model=ManifestDriverResponseDTO)
async def update_manifest_driver(
    manifest_number: str,
    driver_name: str,
    data: ManifestDriverUpdateDTO,
    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 = ManifestDriverService.update(
        db, manifest_number, driver_name, tenant_id, company_id, data
    )
    if not item:
        raise HTTPException(status_code=404, detail="Manifest Driver not found")
    return item


@router.delete("/{manifest_number}/{driver_name}", response_model=bool)
async def delete_manifest_driver(
    manifest_number: str,
    driver_name: str,
    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 = ManifestDriverService.delete(db, manifest_number, driver_name, tenant_id, company_id)
    if not success:
        raise HTTPException(status_code=404, detail="Manifest Driver not found")
    return success
