"""Booking aggregates — Phase 14.1."""
from __future__ import annotations

import uuid
from datetime import date, datetime, time

from sqlalchemy import (
    Boolean,
    Date,
    DateTime,
    Index,
    Integer,
    String,
    Text,
    Time,
    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 (
    AppointmentLifecycleAction,
    AppointmentStatus,
    DayOfWeek,
    GUID,
    LifecycleStatus,
    ScheduleExceptionKind,
)


class StaffSchedule(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "staff_schedules"

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    branch_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    staff_ref: Mapped[str] = mapped_column(String(100), nullable=False)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    day_of_week: Mapped[DayOfWeek] = mapped_column(nullable=False)
    start_time: Mapped[time] = mapped_column(Time, nullable=False)
    end_time: Mapped[time] = mapped_column(Time, nullable=False)
    is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_staff_schedules_tenant_code"),
        Index("ix_staff_schedules_branch", "tenant_id", "branch_id"),
        Index("ix_staff_schedules_staff", "tenant_id", "staff_ref"),
    )


class StaffAvailability(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "staff_availabilities"

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    branch_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    staff_ref: Mapped[str] = mapped_column(String(100), nullable=False)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    starts_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    ends_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    is_bookable: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_staff_availabilities_tenant_code"),
        Index("ix_staff_availabilities_branch", "tenant_id", "branch_id"),
        Index("ix_staff_availabilities_staff", "tenant_id", "staff_ref"),
    )


class ScheduleException(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "schedule_exceptions"

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    branch_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    staff_ref: Mapped[str | None] = mapped_column(String(100), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    kind: Mapped[ScheduleExceptionKind] = mapped_column(nullable=False)
    exception_date: Mapped[date] = mapped_column(Date, nullable=False)
    start_time: Mapped[time | None] = mapped_column(Time, nullable=True)
    end_time: Mapped[time | None] = mapped_column(Time, nullable=True)
    reason: Mapped[str | None] = mapped_column(Text, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_schedule_exceptions_tenant_code"),
        Index("ix_schedule_exceptions_branch", "tenant_id", "branch_id"),
    )


class AppointmentType(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "appointment_types"

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    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)
    default_duration_minutes: Mapped[int] = mapped_column(Integer, default=30, nullable=False)
    status: Mapped[LifecycleStatus] = mapped_column(
        default=LifecycleStatus.ACTIVE, nullable=False
    )

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_appointment_types_tenant_code"),
        Index("ix_appointment_types_org", "tenant_id", "organization_id"),
    )


class Appointment(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    __tablename__ = "appointments"

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    branch_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    appointment_type_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    customer_ref: Mapped[str | None] = mapped_column(String(100), nullable=True)
    staff_ref: Mapped[str | None] = mapped_column(String(100), nullable=True)
    room_ref: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    service_ref: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    status: Mapped[AppointmentStatus] = mapped_column(
        default=AppointmentStatus.REQUESTED, nullable=False
    )
    scheduled_start: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    scheduled_end: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    status_reason: Mapped[str | None] = mapped_column(String(500), nullable=True)
    status_changed_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_appointments_tenant_code"),
        Index("ix_appointments_tenant_status", "tenant_id", "status"),
        Index("ix_appointments_branch", "tenant_id", "branch_id"),
        Index("ix_appointments_staff", "tenant_id", "staff_ref"),
        Index("ix_appointments_scheduled_start", "tenant_id", "scheduled_start"),
    )


class AppointmentStatusHistory(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    __tablename__ = "appointment_status_history"

    appointment_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    action: Mapped[AppointmentLifecycleAction] = mapped_column(nullable=False)
    from_status: Mapped[AppointmentStatus] = mapped_column(nullable=False)
    to_status: Mapped[AppointmentStatus] = mapped_column(nullable=False)
    reason: Mapped[str | None] = mapped_column(String(500), nullable=True)
    actor_user_id: Mapped[str | None] = mapped_column(String(100), nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        Index("ix_appointment_status_history_appt", "tenant_id", "appointment_id"),
    )


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

    organization_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    branch_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    customer_ref: Mapped[str | None] = mapped_column(String(100), nullable=True)
    service_ref: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    preferred_staff_ref: Mapped[str | None] = mapped_column(String(100), nullable=True)
    requested_date: Mapped[date | None] = mapped_column(Date, nullable=True)
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    priority: Mapped[int] = mapped_column(Integer, default=100, nullable=False)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_waiting_list_entries_tenant_code"),
        Index("ix_waiting_list_entries_branch", "tenant_id", "branch_id"),
    )
