"""Fleet management 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 FleetStatus, VehicleStatus
from app.permissions.definitions import (
    FLEETS_CREATE,
    FLEETS_DELETE,
    FLEETS_UPDATE,
    FLEETS_VIEW,
)
from app.queries.fleet import FleetQueries
from app.schemas.fleet import FleetCreate, FleetListResponse, FleetRead, FleetUpdate
from app.specifications.fleet import FLEET_SORT, FleetListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: FleetStatus | None = Query(default=None, alias="status"),
    organization_id: UUID | None = Query(default=None),
    hub_id: UUID | None = Query(default=None),
    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)$"),
) -> FleetListSpec:
    if sort_by not in FLEET_SORT:
        sort_by = "created_at"
    return FleetListSpec(
        status=status_filter,
        organization_id=organization_id,
        hub_id=hub_id,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("", response_model=FleetRead, status_code=status.HTTP_201_CREATED)
async def create_fleet(
    body: FleetCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(FLEETS_CREATE)),
):
    return await FleetCommands(db).create_fleet(tenant_id, body, actor=user)


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


@router.get("/{fleet_id}", response_model=FleetRead)
async def get_fleet(
    fleet_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(FLEETS_VIEW)),
):
    return await FleetQueries(db).get_fleet(tenant_id, fleet_id)


@router.patch("/{fleet_id}", response_model=FleetRead)
async def update_fleet(
    fleet_id: UUID,
    body: FleetUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(FLEETS_UPDATE)),
):
    return await FleetCommands(db).update_fleet(tenant_id, fleet_id, body, actor=user)


@router.post("/{fleet_id}/delete", response_model=FleetRead)
async def delete_fleet(
    fleet_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(FLEETS_DELETE)),
):
    return await FleetCommands(db).delete_fleet(tenant_id, fleet_id, actor=user)
