"""Table Service & Reservations aggregates — Phase 12.3.

Dine-in table service workflows: guest reservations, table assignments,
in-service requests, and walk-in waitlist. POS / kitchen / payment engines
are out of scope.
"""
from __future__ import annotations

import uuid
from datetime import datetime

from sqlalchemy import (
    DateTime,
    Index,
    Integer,
    String,
    Text,
    UniqueConstraint,
)
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.types import JSON

from app.core.database import Base
from app.models.base import (
    ActorAuditMixin,
    SoftDeleteMixin,
    TenantMixin,
    TimestampMixin,
    UUIDPrimaryKeyMixin,
)
from app.models.types import (
    GUID,
    ReservationStatus,
    ServiceRequestKind,
    ServiceRequestStatus,
    TableAssignmentStatus,
    WaitlistStatus,
)


class Reservation(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Guest reservation for a future dine-in window."""

    __tablename__ = "reservations"

    venue_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    branch_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    dining_area_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    table_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    guest_name: Mapped[str] = mapped_column(String(255), nullable=False)
    guest_phone: Mapped[str | None] = mapped_column(String(32), nullable=True)
    party_size: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    status: Mapped[ReservationStatus] = mapped_column(
        default=ReservationStatus.PENDING, nullable=False
    )
    reserved_from: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    reserved_to: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "venue_id", "code", name="uq_reservations_tenant_venue_code"
        ),
        Index("ix_reservations_venue", "tenant_id", "venue_id"),
        Index("ix_reservations_table", "tenant_id", "table_id"),
        Index("ix_reservations_status", "tenant_id", "status"),
        Index("ix_reservations_tenant_deleted", "tenant_id", "is_deleted"),
    )


class TableAssignment(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """A table occupied for service, optionally linked to a reservation / ordering session."""

    __tablename__ = "table_assignments"

    venue_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    table_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    reservation_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    ordering_session_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    status: Mapped[TableAssignmentStatus] = mapped_column(
        default=TableAssignmentStatus.ACTIVE, nullable=False
    )
    assigned_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    released_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    guest_label: Mapped[str | None] = mapped_column(String(255), nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        Index("ix_table_assignments_venue", "tenant_id", "venue_id"),
        Index("ix_table_assignments_table", "tenant_id", "table_id"),
        Index("ix_table_assignments_status", "tenant_id", "status"),
        Index("ix_table_assignments_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ServiceRequest(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """A guest-initiated in-service request (call waiter, water, bill, other)."""

    __tablename__ = "service_requests"

    venue_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    table_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    table_assignment_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    kind: Mapped[ServiceRequestKind] = mapped_column(
        default=ServiceRequestKind.OTHER, nullable=False
    )
    status: Mapped[ServiceRequestStatus] = mapped_column(
        default=ServiceRequestStatus.OPEN, nullable=False
    )
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "venue_id", "code", name="uq_service_requests_tenant_venue_code"
        ),
        Index("ix_service_requests_venue", "tenant_id", "venue_id"),
        Index("ix_service_requests_table", "tenant_id", "table_id"),
        Index("ix_service_requests_status", "tenant_id", "status"),
        Index("ix_service_requests_tenant_deleted", "tenant_id", "is_deleted"),
    )


class WaitlistEntry(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    """Walk-in guest waiting for a table."""

    __tablename__ = "waitlist_entries"

    venue_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    guest_name: Mapped[str] = mapped_column(String(255), nullable=False)
    party_size: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    status: Mapped[WaitlistStatus] = mapped_column(
        default=WaitlistStatus.WAITING, nullable=False
    )
    phone: Mapped[str | None] = mapped_column(String(32), nullable=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "venue_id", "code", name="uq_waitlist_entries_tenant_venue_code"
        ),
        Index("ix_waitlist_entries_venue", "tenant_id", "venue_id"),
        Index("ix_waitlist_entries_status", "tenant_id", "status"),
        Index("ix_waitlist_entries_tenant_deleted", "tenant_id", "is_deleted"),
    )
