"""Appointment scheduling aggregates — Phase 13.1."""
from __future__ import annotations

import uuid
from datetime import datetime, time

from sqlalchemy import Boolean, 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 AppointmentStatus, DayOfWeek, GUID, LifecycleStatus


class Schedule(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "schedules"

    clinic_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    doctor_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    department_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)
    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)
    slot_duration_minutes: Mapped[int] = mapped_column(Integer, default=30, 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_schedules_tenant_code"),
        Index("ix_schedules_doctor", "tenant_id", "doctor_id"),
        Index("ix_schedules_clinic", "tenant_id", "clinic_id"),
    )


class AvailabilityWindow(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "availability_windows"

    clinic_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    doctor_id: Mapped[uuid.UUID] = mapped_column(GUID(), 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_availability_windows_tenant_code"),
        Index("ix_availability_windows_doctor", "tenant_id", "doctor_id"),
        Index("ix_availability_windows_starts", "tenant_id", "starts_at"),
    )


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

    clinic_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_clinic", "tenant_id", "clinic_id"),
    )


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

    clinic_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    doctor_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    patient_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    department_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    appointment_type_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    status: Mapped[AppointmentStatus] = mapped_column(
        default=AppointmentStatus.DRAFT, 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
    )
    reminder_scheduled: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
    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_doctor", "tenant_id", "doctor_id"),
        Index("ix_appointments_patient", "tenant_id", "patient_id"),
        Index("ix_appointments_scheduled_start", "tenant_id", "scheduled_start"),
    )


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

    clinic_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    doctor_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    patient_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)
    preferred_date: Mapped[str | None] = mapped_column(String(32), 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_clinic", "tenant_id", "clinic_id"),
        Index("ix_waiting_list_entries_patient", "tenant_id", "patient_id"),
    )
