"""Pharmacy network aggregates — Phase 13.6."""
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, LifecycleStatus, PrescriptionOrderStatus


class Pharmacy(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    __tablename__ = "pharmacies"

    code: Mapped[str] = mapped_column(String(50), nullable=False)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    contact: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    hours: Mapped[dict | None] = mapped_column(JSON, nullable=True)
    service_area_ref: Mapped[str | None] = mapped_column(String(255), 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", "code", name="uq_pharmacies_tenant_code"),
        Index("ix_pharmacies_tenant", "tenant_id", "status"),
    )


class PrescriptionOrder(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
    OptimisticLockMixin,
):
    __tablename__ = "prescription_orders"

    pharmacy_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    encounter_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    visit_session_id: Mapped[uuid.UUID | None] = mapped_column(GUID(), nullable=True)
    patient_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)
    status: Mapped[PrescriptionOrderStatus] = mapped_column(
        default=PrescriptionOrderStatus.SUBMITTED, nullable=False
    )
    status_changed_at: Mapped[datetime | None] = mapped_column(
        DateTime(timezone=True), nullable=True
    )
    notes: Mapped[str | None] = mapped_column(Text, nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint("tenant_id", "code", name="uq_prescription_orders_tenant_code"),
        Index("ix_prescription_orders_pharmacy", "tenant_id", "pharmacy_id"),
        Index("ix_prescription_orders_status", "tenant_id", "status"),
    )


class PrescriptionLine(
    Base,
    UUIDPrimaryKeyMixin,
    TenantMixin,
    TimestampMixin,
    SoftDeleteMixin,
    ActorAuditMixin,
):
    __tablename__ = "prescription_lines"

    prescription_order_id: Mapped[uuid.UUID] = mapped_column(GUID(), nullable=False)
    line_no: Mapped[int] = mapped_column(Integer, nullable=False)
    medication_code: Mapped[str] = mapped_column(String(100), nullable=False)
    display: Mapped[str] = mapped_column(String(255), nullable=False)
    quantity: Mapped[int] = mapped_column(Integer, default=1, nullable=False)
    dosage_instructions: Mapped[str | None] = mapped_column(String(255), nullable=True)
    metadata_json: Mapped[dict | None] = mapped_column(JSON, nullable=True)

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "prescription_order_id",
            "line_no",
            name="uq_prescription_lines_order_line",
        ),
        Index("ix_prescription_lines_order", "tenant_id", "prescription_order_id"),
    )


class PrescriptionStatusHistory(Base, UUIDPrimaryKeyMixin, TenantMixin, TimestampMixin):
    __tablename__ = "prescription_status_history"

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

    __table_args__ = (
        Index("ix_prescription_status_history_order", "tenant_id", "prescription_order_id"),
    )
