"""Dispatch assignment APIs — Phase 10.5."""
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.dispatch import DispatchCommands
from app.models.types import JobAssignmentStatus
from app.permissions.definitions import (
    DISPATCH_ASSIGNMENTS_CREATE,
    DISPATCH_ASSIGNMENTS_UPDATE,
    DISPATCH_ASSIGNMENTS_VIEW,
)
from app.queries.dispatch import DispatchQueries
from app.schemas.dispatch import (
    JobAssignmentCreate,
    JobAssignmentListResponse,
    JobAssignmentRead,
    JobAssignmentUpdate,
)
from app.specifications.dispatch import JobAssignmentListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    dispatch_job_id: UUID | None = Query(default=None),
    driver_id: UUID | None = Query(default=None),
    status_filter: JobAssignmentStatus | None = Query(default=None, alias="status"),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> JobAssignmentListSpec:
    return JobAssignmentListSpec(
        dispatch_job_id=dispatch_job_id,
        driver_id=driver_id,
        status=status_filter,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("", response_model=JobAssignmentRead, status_code=status.HTTP_201_CREATED)
async def create_assignment(
    body: JobAssignmentCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DISPATCH_ASSIGNMENTS_CREATE)),
):
    return await DispatchCommands(db).create_assignment(tenant_id, body, actor=user)


@router.get("", response_model=JobAssignmentListResponse)
async def list_assignments(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: JobAssignmentListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(DISPATCH_ASSIGNMENTS_VIEW)),
):
    items, total = await DispatchQueries(db).list_assignments(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return JobAssignmentListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{assignment_id}", response_model=JobAssignmentRead)
async def get_assignment(
    assignment_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(DISPATCH_ASSIGNMENTS_VIEW)),
):
    return await DispatchQueries(db).get_assignment(tenant_id, assignment_id)


@router.patch("/{assignment_id}", response_model=JobAssignmentRead)
async def update_assignment(
    assignment_id: UUID,
    body: JobAssignmentUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DISPATCH_ASSIGNMENTS_UPDATE)),
):
    return await DispatchCommands(db).update_assignment(
        tenant_id, assignment_id, body, actor=user
    )
