"""Pharmacy network DTOs — Phase 13.6."""
from __future__ import annotations

from datetime import datetime
from uuid import UUID

from pydantic import BaseModel, ConfigDict, Field

from app.models.types import LifecycleStatus, PrescriptionOrderStatus
from app.schemas.common import ORMBase

_FORBID = ConfigDict(extra="forbid")


class PharmacyCreate(BaseModel):
    model_config = _FORBID
    code: str = Field(max_length=50)
    name: str = Field(max_length=255)
    contact: dict | None = None
    hours: dict | None = None
    service_area_ref: str | None = Field(default=None, max_length=255)
    status: LifecycleStatus = LifecycleStatus.ACTIVE
    metadata_json: dict | None = None


class PharmacyRead(ORMBase):
    id: UUID
    tenant_id: UUID
    code: str
    name: str
    contact: dict | None
    hours: dict | None
    service_area_ref: str | None
    status: LifecycleStatus
    metadata_json: dict | None
    version: int
    is_deleted: bool
    created_at: datetime
    updated_at: datetime


class PrescriptionLineCreate(BaseModel):
    model_config = _FORBID
    line_no: int = Field(ge=1)
    medication_code: str = Field(max_length=100)
    display: str = Field(max_length=255)
    quantity: int = Field(default=1, ge=1)
    dosage_instructions: str | None = Field(default=None, max_length=255)
    metadata_json: dict | None = None


class PrescriptionOrderCreate(BaseModel):
    model_config = _FORBID
    pharmacy_id: UUID
    encounter_id: UUID | None = None
    visit_session_id: UUID | None = None
    patient_id: UUID
    doctor_id: UUID
    code: str = Field(max_length=50)
    notes: str | None = None
    lines: list[PrescriptionLineCreate]
    metadata_json: dict | None = None


class PrescriptionLifecycleRequest(BaseModel):
    model_config = _FORBID
    version: int = Field(ge=1)
    reason: str | None = Field(default=None, max_length=500)


class PrescriptionLineRead(ORMBase):
    id: UUID
    tenant_id: UUID
    prescription_order_id: UUID
    line_no: int
    medication_code: str
    display: str
    quantity: int
    dosage_instructions: str | None
    metadata_json: dict | None
    is_deleted: bool
    created_at: datetime
    updated_at: datetime


class PrescriptionOrderRead(ORMBase):
    id: UUID
    tenant_id: UUID
    pharmacy_id: UUID
    encounter_id: UUID | None
    visit_session_id: UUID | None
    patient_id: UUID
    doctor_id: UUID
    code: str
    status: PrescriptionOrderStatus
    status_changed_at: datetime | None
    notes: str | None
    metadata_json: dict | None
    version: int
    is_deleted: bool
    created_at: datetime
    updated_at: datetime
