"""Dispatch query specifications — Phase 10.5."""
from __future__ import annotations

from dataclasses import dataclass
from uuid import UUID

from sqlalchemy import Select, asc, desc, or_
from sqlalchemy.sql import ColumnElement

from app.models.dispatch import DispatchJob, JobAssignment
from app.models.types import DispatchJobStatus, JobAssignmentStatus

JOB_SORT = frozenset({"created_at", "updated_at", "code", "status", "priority"})
ASSIGN_SORT = frozenset({"created_at", "updated_at", "status"})


@dataclass(frozen=True, slots=True)
class DispatchJobListSpec:
    status: DispatchJobStatus | None = None
    organization_id: UUID | None = None
    hub_id: UUID | None = None
    q: str | None = None
    sort_by: str = "created_at"
    sort_dir: str = "desc"

    def filter_clauses(self) -> list[ColumnElement]:
        clauses: list[ColumnElement] = []
        if self.status is not None:
            clauses.append(DispatchJob.status == self.status)
        if self.organization_id is not None:
            clauses.append(DispatchJob.organization_id == self.organization_id)
        if self.hub_id is not None:
            clauses.append(DispatchJob.hub_id == self.hub_id)
        if self.q:
            term = f"%{self.q.strip()}%"
            clauses.append(
                or_(
                    DispatchJob.code.ilike(term),
                    DispatchJob.external_order_ref.ilike(term),
                )
            )
        return clauses

    def apply(self, stmt: Select) -> Select:
        clauses = self.filter_clauses()
        if clauses:
            stmt = stmt.where(*clauses)
        sort_key = self.sort_by if self.sort_by in JOB_SORT else "created_at"
        column = getattr(DispatchJob, sort_key)
        order = desc(column) if self.sort_dir.lower() != "asc" else asc(column)
        return stmt.order_by(order)


@dataclass(frozen=True, slots=True)
class JobAssignmentListSpec:
    dispatch_job_id: UUID | None = None
    driver_id: UUID | None = None
    status: JobAssignmentStatus | None = None
    sort_by: str = "created_at"
    sort_dir: str = "desc"

    def filter_clauses(self) -> list[ColumnElement]:
        clauses: list[ColumnElement] = []
        if self.dispatch_job_id is not None:
            clauses.append(JobAssignment.dispatch_job_id == self.dispatch_job_id)
        if self.driver_id is not None:
            clauses.append(JobAssignment.driver_id == self.driver_id)
        if self.status is not None:
            clauses.append(JobAssignment.status == self.status)
        return clauses

    def apply(self, stmt: Select) -> Select:
        clauses = self.filter_clauses()
        if clauses:
            stmt = stmt.where(*clauses)
        sort_key = self.sort_by if self.sort_by in ASSIGN_SORT else "created_at"
        column = getattr(JobAssignment, sort_key)
        order = desc(column) if self.sort_dir.lower() != "asc" else asc(column)
        return stmt.order_by(order)
