"""Settlement query specifications — Phase 10.8."""
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.settlement import SettlementIntent
from app.models.types import SettlementIntentStatus

INTENT_SORT = frozenset({"created_at", "updated_at", "code", "status"})


@dataclass(frozen=True, slots=True)
class SettlementIntentListSpec:
    status: SettlementIntentStatus | None = None
    organization_id: UUID | None = None
    driver_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(SettlementIntent.status == self.status)
        if self.organization_id is not None:
            clauses.append(SettlementIntent.organization_id == self.organization_id)
        if self.driver_id is not None:
            clauses.append(SettlementIntent.driver_id == self.driver_id)
        if self.q:
            term = f"%{self.q.strip()}%"
            clauses.append(SettlementIntent.code.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 INTENT_SORT else "created_at"
        column = getattr(SettlementIntent, sort_key)
        order = desc(column) if self.sort_dir.lower() != "asc" else asc(column)
        return stmt.order_by(order)
