"""Scheduling & Booking aggregates — Phase 9.4."""
from __future__ import annotations

import uuid
from datetime import datetime

from sqlalchemy import Boolean, 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,
    OptimisticLockMixin,
    SoftDeleteMixin,
    TenantMixin,
    TimestampMixin,
    UUIDPrimaryKeyMixin,
)
from app.models.types import (
    BookingStatus,
    GUID,
    LifecycleStatus,
    RecurrenceKind,
    SessionKind,
    WaitlistStatus,
)


class Equipment(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "equipment"

    sports_center_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    branch_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    facility_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    status: Mapped[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.ACTIVE, nullable=False
    )
    quantity_total: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    quantity_available: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    attributes: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "sports_center_id", "code", name="uq_equipment_tenant_code"
        ),
        Index("ix_equipment_center", "tenant_id", "sports_center_id"),
        Index("ix_equipment_tenant_deleted", "tenant_id", "is_deleted"),
    )


class SportsSession(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    __tablename__ = "sports_sessions"

    sports_center_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    branch_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    title: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[str | None] = mapped_column(Text, nullable=True)
    session_kind: Mapped[SessionKind] = mapped_column(
        default=SessionKind.CLASS, nullable=False
    )
    sport_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    coach_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    facility_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    court_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    room_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    starts_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    ends_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    capacity: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    booked_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    waitlist_count: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
    recurrence_kind: Mapped[RecurrenceKind] = mapped_column(
        default=RecurrenceKind.NONE, nullable=False
    )
    recurrence_rule: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    status: Mapped[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.ACTIVE, nullable=False
    )
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "sports_center_id", "code", name="uq_sports_sessions_tenant_code"
        ),
        Index("ix_sports_sessions_center", "tenant_id", "sports_center_id"),
        Index("ix_sports_sessions_window", "tenant_id", "starts_at", "ends_at"),
        Index("ix_sports_sessions_coach", "tenant_id", "coach_id"),
        Index("ix_sports_sessions_tenant_deleted", "tenant_id", "is_deleted"),
    )


class Booking(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    __tablename__ = "bookings"

    sports_center_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    session_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    member_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    membership_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    booking_number: Mapped[str] = mapped_column(String(50), nullable=False)
    status: Mapped[BookingStatus] = mapped_column(
        default=BookingStatus.PENDING, nullable=False
    )
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    confirmed_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    cancelled_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    cancellation_reason: Mapped[str | None] = mapped_column(String(255), nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id", "booking_number", name="uq_bookings_tenant_number"
        ),
        Index("ix_bookings_session", "tenant_id", "session_id"),
        Index("ix_bookings_member", "tenant_id", "member_id"),
        Index("ix_bookings_tenant_status", "tenant_id", "status"),
        Index("ix_bookings_tenant_deleted", "tenant_id", "is_deleted"),
    )


class WaitingListEntry(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "waiting_list_entries"

    sports_center_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    session_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    member_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    position: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    status: Mapped[WaitlistStatus] = mapped_column(
        default=WaitlistStatus.WAITING, nullable=False
    )
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        Index("ix_waiting_list_session", "tenant_id", "session_id"),
        Index("ix_waiting_list_member", "tenant_id", "member_id"),
        Index("ix_waiting_list_tenant_deleted", "tenant_id", "is_deleted"),
    )


class ResourceReservation(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "resource_reservations"

    sports_center_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    session_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    booking_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    facility_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    equipment_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    starts_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    ends_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    quantity: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    status: Mapped[BookingStatus] = mapped_column(
        default=BookingStatus.CONFIRMED, nullable=False
    )
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        Index("ix_resource_reservations_window", "tenant_id", "starts_at", "ends_at"),
        Index("ix_resource_reservations_facility", "tenant_id", "facility_id"),
        Index("ix_resource_reservations_equipment", "tenant_id", "equipment_id"),
        Index("ix_resource_reservations_tenant_deleted", "tenant_id", "is_deleted"),
    )
