"""Route plan APIs — Phase 10.6."""
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.routing import RoutingCommands
from app.models.types import RoutePlanStatus
from app.permissions.definitions import (
    ROUTES_CREATE,
    ROUTES_DELETE,
    ROUTES_STOPS_MANAGE,
    ROUTES_STOPS_VIEW,
    ROUTES_UPDATE,
    ROUTES_VIEW,
)
from app.queries.routing import RoutingQueries
from app.schemas.routing import (
    RoutePlanCreate,
    RoutePlanListResponse,
    RoutePlanRead,
    RoutePlanUpdate,
    RouteStopCreate,
    RouteStopRead,
)
from app.specifications.routing import RoutePlanListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: RoutePlanStatus | None = Query(default=None, alias="status"),
    organization_id: UUID | None = Query(default=None),
    driver_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)$"),
) -> RoutePlanListSpec:
    return RoutePlanListSpec(
        status=status_filter,
        organization_id=organization_id,
        driver_id=driver_id,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("", response_model=RoutePlanRead, status_code=status.HTTP_201_CREATED)
async def create_route(
    body: RoutePlanCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ROUTES_CREATE)),
):
    return await RoutingCommands(db).create_route(tenant_id, body, actor=user)


@router.get("", response_model=RoutePlanListResponse)
async def list_routes(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: RoutePlanListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(ROUTES_VIEW)),
):
    items, total = await RoutingQueries(db).list_routes(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return RoutePlanListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{plan_id}", response_model=RoutePlanRead)
async def get_route(
    plan_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(ROUTES_VIEW)),
):
    return await RoutingQueries(db).get_route(tenant_id, plan_id)


@router.patch("/{plan_id}", response_model=RoutePlanRead)
async def update_route(
    plan_id: UUID,
    body: RoutePlanUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ROUTES_UPDATE)),
):
    return await RoutingCommands(db).update_route(tenant_id, plan_id, body, actor=user)


@router.post("/{plan_id}/delete", response_model=RoutePlanRead)
async def delete_route(
    plan_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ROUTES_DELETE)),
):
    return await RoutingCommands(db).delete_route(tenant_id, plan_id, actor=user)


@router.post(
    "/{plan_id}/stops",
    response_model=RouteStopRead,
    status_code=status.HTTP_201_CREATED,
)
async def add_stop(
    plan_id: UUID,
    body: RouteStopCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(ROUTES_STOPS_MANAGE)),
):
    return await RoutingCommands(db).add_stop(tenant_id, plan_id, body, actor=user)


@router.get("/{plan_id}/stops", response_model=list[RouteStopRead])
async def list_stops(
    plan_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(ROUTES_STOPS_VIEW)),
):
    return await RoutingQueries(db).list_stops(tenant_id, plan_id)
