"""Dispatch job 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 DispatchJobStatus
from app.permissions.definitions import (
    DISPATCH_JOBS_CREATE,
    DISPATCH_JOBS_DELETE,
    DISPATCH_JOBS_STATUS,
    DISPATCH_JOBS_UPDATE,
    DISPATCH_JOBS_VIEW,
)
from app.queries.dispatch import DispatchQueries
from app.schemas.dispatch import (
    DispatchJobCreate,
    DispatchJobListResponse,
    DispatchJobRead,
    DispatchJobStatusRequest,
    DispatchJobUpdate,
)
from app.specifications.dispatch import DispatchJobListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: DispatchJobStatus | 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)$"),
) -> DispatchJobListSpec:
    return DispatchJobListSpec(
        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=DispatchJobRead, status_code=status.HTTP_201_CREATED)
async def create_dispatch_job(
    body: DispatchJobCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DISPATCH_JOBS_CREATE)),
):
    return await DispatchCommands(db).create_job(tenant_id, body, actor=user)


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


@router.get("/{job_id}", response_model=DispatchJobRead)
async def get_dispatch_job(
    job_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(DISPATCH_JOBS_VIEW)),
):
    return await DispatchQueries(db).get_job(tenant_id, job_id)


@router.patch("/{job_id}", response_model=DispatchJobRead)
async def update_dispatch_job(
    job_id: UUID,
    body: DispatchJobUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DISPATCH_JOBS_UPDATE)),
):
    return await DispatchCommands(db).update_job(tenant_id, job_id, body, actor=user)


@router.post("/{job_id}/status", response_model=DispatchJobRead)
async def apply_dispatch_status(
    job_id: UUID,
    body: DispatchJobStatusRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DISPATCH_JOBS_STATUS)),
):
    return await DispatchCommands(db).apply_status(
        tenant_id, job_id, body, actor=user
    )


@router.post("/{job_id}/delete", response_model=DispatchJobRead)
async def delete_dispatch_job(
    job_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(DISPATCH_JOBS_DELETE)),
):
    return await DispatchCommands(db).delete_job(tenant_id, job_id, actor=user)
