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, status
from sqlalchemy.orm import Session

from .dto import DriverCreateDTO, DriverResponseDTO
from .models import Driver
from .services import DriverService

router = APIRouter(prefix="/drivers")


@router.get("/", response_model=Dict[str, Any])
async def list_drivers(
    company_id: int = Query(..., description="Company ID for filtering"),
    page: int = Query(1, ge=1, description="Page number"),
    page_size: int = Query(50, ge=1, le=100, description="Page size"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    drivers = DriverService.list_drivers(db, str(company_id), tenant_id)
    total = len(drivers)
    
    # Aplicar paginación manualmente
    skip = (page - 1) * page_size
    paginated_drivers = drivers[skip : skip + page_size]
    
    return {
        "items": [DriverResponseDTO.model_validate(driver) for driver in paginated_drivers],
        "total": total,
        "page": page,
        "page_size": page_size,
    }


@router.get("/{transporter_key}/{line}", response_model=DriverResponseDTO)
async def read_driver(
    transporter_key: str,
    line: int,
    company_id: int = Query(..., description="Company ID for filtering"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    driver = DriverService.get_driver_by_key_and_line(
        db, transporter_key, line, str(company_id), tenant_id
    )
    if not driver:
        raise HTTPException(status_code=404, detail="Driver not found")
    return driver


@router.post("/", response_model=DriverResponseDTO, status_code=status.HTTP_201_CREATED)
async def create_driver(
    driver_data: DriverCreateDTO,
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    return DriverService.create_driver(db, driver_data)


@router.delete("/{transporter_key}/{line}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_driver(
    transporter_key: str,
    line: int,
    company_id: int = Query(..., description="Company ID for filtering"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    driver = DriverService.delete_driver(
        db, transporter_key, line, str(company_id), tenant_id
    )
    if not driver:
        raise HTTPException(status_code=404, detail="Driver not found")
