"""Vehicle APIs — Phase 10.2."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination, require_tenant
from app.api.permissions import require_permissions
from app.commands.fleet import FleetCommands
from app.models.types import VehicleStatus
from app.permissions.definitions import (
    VEHICLES_ASSIGNMENTS_MANAGE,
    VEHICLES_ASSIGNMENTS_VIEW,
    VEHICLES_CREATE,
    VEHICLES_DELETE,
    VEHICLES_UPDATE,
    VEHICLES_VIEW,
)
from app.queries.fleet import FleetQueries
from app.schemas.fleet import (
    VehicleAssignmentCreate,
    VehicleAssignmentRead,
    VehicleAssignmentUpdate,
    VehicleCreate,
    VehicleListResponse,
    VehicleRead,
    VehicleUpdate,
)
from app.specifications.fleet import VehicleListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    fleet_id: UUID | None = Query(default=None),
    status_filter: VehicleStatus | None = Query(default=None, alias="status"),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> VehicleListSpec:
    return VehicleListSpec(
        fleet_id=fleet_id,
        status=status_filter,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("", response_model=VehicleRead, status_code=status.HTTP_201_CREATED)
async def create_vehicle(
    body: VehicleCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(VEHICLES_CREATE)),
):
    return await FleetCommands(db).create_vehicle(tenant_id, body, actor=user)


@router.get("", response_model=VehicleListResponse)
async def list_vehicles(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: VehicleListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(VEHICLES_VIEW)),
):
    items, total = await FleetQueries(db).list_vehicles(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return VehicleListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{vehicle_id}", response_model=VehicleRead)
async def get_vehicle(
    vehicle_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(VEHICLES_VIEW)),
):
    return await FleetQueries(db).get_vehicle(tenant_id, vehicle_id)


@router.patch("/{vehicle_id}", response_model=VehicleRead)
async def update_vehicle(
    vehicle_id: UUID,
    body: VehicleUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(VEHICLES_UPDATE)),
):
    return await FleetCommands(db).update_vehicle(
        tenant_id, vehicle_id, body, actor=user
    )


@router.post("/{vehicle_id}/delete", response_model=VehicleRead)
async def delete_vehicle(
    vehicle_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(VEHICLES_DELETE)),
):
    return await FleetCommands(db).delete_vehicle(tenant_id, vehicle_id, actor=user)


@router.post(
    "/{vehicle_id}/assignments",
    response_model=VehicleAssignmentRead,
    status_code=status.HTTP_201_CREATED,
)
async def create_assignment(
    vehicle_id: UUID,
    body: VehicleAssignmentCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(VEHICLES_ASSIGNMENTS_MANAGE)),
):
    return await FleetCommands(db).create_assignment(
        tenant_id, vehicle_id, body, actor=user
    )


@router.get("/{vehicle_id}/assignments", response_model=list[VehicleAssignmentRead])
async def list_assignments(
    vehicle_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(VEHICLES_ASSIGNMENTS_VIEW)),
):
    return await FleetQueries(db).list_assignments(tenant_id, vehicle_id)


@router.patch(
    "/{vehicle_id}/assignments/{assignment_id}",
    response_model=VehicleAssignmentRead,
)
async def update_assignment(
    vehicle_id: UUID,
    assignment_id: UUID,
    body: VehicleAssignmentUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(VEHICLES_ASSIGNMENTS_MANAGE)),
):
    return await FleetCommands(db).update_assignment(
        tenant_id, vehicle_id, assignment_id, body, actor=user
    )
