"""Availability query specifications — Phase 10.3."""
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.availability import Shift, WorkingZone
from app.models.types import ShiftStatus, WorkingZoneStatus

SHIFT_SORT = frozenset({"created_at", "starts_at", "ends_at", "code", "status"})
ZONE_SORT = frozenset({"created_at", "updated_at", "code", "name", "status"})


@dataclass(frozen=True, slots=True)
class ShiftListSpec:
    status: ShiftStatus | None = None
    organization_id: UUID | None = None
    hub_id: UUID | None = None
    q: str | None = None
    sort_by: str = "starts_at"
    sort_dir: str = "desc"

    def filter_clauses(self) -> list[ColumnElement]:
        clauses: list[ColumnElement] = []
        if self.status is not None:
            clauses.append(Shift.status == self.status)
        if self.organization_id is not None:
            clauses.append(Shift.organization_id == self.organization_id)
        if self.hub_id is not None:
            clauses.append(Shift.hub_id == self.hub_id)
        if self.q:
            term = f"%{self.q.strip()}%"
            clauses.append(or_(Shift.code.ilike(term), Shift.name.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 SHIFT_SORT else "starts_at"
        column = getattr(Shift, 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 WorkingZoneListSpec:
    status: WorkingZoneStatus | None = None
    organization_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(WorkingZone.status == self.status)
        if self.organization_id is not None:
            clauses.append(WorkingZone.organization_id == self.organization_id)
        if self.q:
            term = f"%{self.q.strip()}%"
            clauses.append(
                or_(WorkingZone.code.ilike(term), WorkingZone.name.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 ZONE_SORT else "created_at"
        column = getattr(WorkingZone, sort_key)
        order = desc(column) if self.sort_dir.lower() != "asc" else asc(column)
        return stmt.order_by(order)
