"""Table Service & Reservations repositories — Phase 12.3."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select

from app.models.table_service import (
    Reservation,
    ServiceRequest,
    TableAssignment,
    WaitlistEntry,
)
from app.repositories.base import TenantBaseRepository


class ReservationRepository(TenantBaseRepository[Reservation]):
    model = Reservation

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


class TableAssignmentRepository(TenantBaseRepository[TableAssignment]):
    model = TableAssignment

    async def list_active_for_table(self, tenant_id: UUID, table_id: UUID):
        from app.models.types import TableAssignmentStatus

        stmt = select(TableAssignment).where(
            TableAssignment.tenant_id == tenant_id,
            TableAssignment.table_id == table_id,
            TableAssignment.status == TableAssignmentStatus.ACTIVE,
            TableAssignment.is_deleted.is_(False),
        )
        result = await self.session.execute(stmt)
        return result.scalars().all()


class ServiceRequestRepository(TenantBaseRepository[ServiceRequest]):
    model = ServiceRequest

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


class WaitlistEntryRepository(TenantBaseRepository[WaitlistEntry]):
    model = WaitlistEntry

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