"""Doctor panel aggregates — Phase 13.2."""
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,
    OptimisticLockMixin,
    SoftDeleteMixin,
    TenantMixin,
    TimestampMixin,
    UUIDPrimaryKeyMixin,
)
from app.models.types import GUID, VisitSessionStatus


class VisitSession(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    __tablename__ = "visit_sessions"

    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)
    appointment_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    code: Mapped[str] = mapped_column(String(50), nullable=False)
    status: Mapped[VisitSessionStatus] = mapped_column(
        default=VisitSessionStatus.QUEUED, nullable=False
    )
    queue_position: Mapped[int] = mapped_column(Integer, default=100, nullable=False)
    started_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
    finished_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_visit_sessions_tenant_code"),
        Index("ix_visit_sessions_doctor", "tenant_id", "doctor_id"),
        Index("ix_visit_sessions_appointment", "tenant_id", "appointment_id"),
    )


class VisitNote(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    __tablename__ = "visit_notes"

    visit_session_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)
    title: Mapped[str] = mapped_column(String(255), nullable=False)
    body: Mapped[str | None] = mapped_column(Text, nullable=True)
    storage_file_ref: Mapped[str | None] = mapped_column(String(255), nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_visit_notes_tenant_code"),
        Index("ix_visit_notes_session", "tenant_id", "visit_session_id"),
    )
