"""Appointment repositories — Phase 14.1."""
from __future__ import annotations

from typing import Sequence
from uuid import UUID

from sqlalchemy import select

from app.models.appointments import Appointment, AppointmentStatusHistory
from app.repositories.base import TenantBaseRepository


class AppointmentRepository(TenantBaseRepository[Appointment]):
    model = Appointment

    async def get_by_code(self, tenant_id: UUID, code: str) -> Appointment | None:
        stmt = select(self.model).where(
            self.model.tenant_id == tenant_id,
            self.model.code == code,
            self.model.is_deleted.is_(False),
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()


class AppointmentStatusHistoryRepository(TenantBaseRepository[AppointmentStatusHistory]):
    model = AppointmentStatusHistory

    async def list_for_appointment(
        self, tenant_id: UUID, appointment_id: UUID, *, limit: int = 100
    ) -> Sequence[AppointmentStatusHistory]:
        stmt = (
            select(self.model)
            .where(
                self.model.tenant_id == tenant_id,
                self.model.appointment_id == appointment_id,
            )
            .order_by(self.model.created_at.desc())
            .limit(limit)
        )
        result = await self.session.execute(stmt)
        return result.scalars().all()
