"""Proof of delivery APIs — Phase 10.7."""
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.tracking import TrackingCommands
from app.models.types import ProofOfDeliveryStatus
from app.permissions.definitions import (
    PROOF_OF_DELIVERY_CREATE,
    PROOF_OF_DELIVERY_UPDATE,
    PROOF_OF_DELIVERY_VIEW,
)
from app.queries.tracking import TrackingQueries
from app.schemas.tracking import (
    ProofOfDeliveryCreate,
    ProofOfDeliveryListResponse,
    ProofOfDeliveryRead,
    ProofOfDeliveryUpdate,
)
from app.specifications.tracking import ProofOfDeliveryListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


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


@router.post("", response_model=ProofOfDeliveryRead, status_code=status.HTTP_201_CREATED)
async def capture_pod(
    body: ProofOfDeliveryCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(PROOF_OF_DELIVERY_CREATE)),
):
    return await TrackingCommands(db).capture_pod(tenant_id, body, actor=user)


@router.get("", response_model=ProofOfDeliveryListResponse)
async def list_pods(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: ProofOfDeliveryListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(PROOF_OF_DELIVERY_VIEW)),
):
    items, total = await TrackingQueries(db).list_pods(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return ProofOfDeliveryListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{pod_id}", response_model=ProofOfDeliveryRead)
async def get_pod(
    pod_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(PROOF_OF_DELIVERY_VIEW)),
):
    return await TrackingQueries(db).get_pod(tenant_id, pod_id)


@router.patch("/{pod_id}", response_model=ProofOfDeliveryRead)
async def update_pod(
    pod_id: UUID,
    body: ProofOfDeliveryUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(PROOF_OF_DELIVERY_UPDATE)),
):
    return await TrackingCommands(db).update_pod(tenant_id, pod_id, body, actor=user)
