"""Pharmacy repositories — Phase 13.6."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select

from app.models.pharmacy import Pharmacy, PrescriptionLine, PrescriptionOrder, PrescriptionStatusHistory
from app.repositories.base import TenantBaseRepository


class PharmacyRepository(TenantBaseRepository[Pharmacy]):
    model = Pharmacy

    async def get_by_code(self, tenant_id: UUID, code: str) -> Pharmacy | None:
        stmt = select(Pharmacy).where(
            Pharmacy.tenant_id == tenant_id,
            Pharmacy.code == code,
            Pharmacy.is_deleted.is_(False),
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()


class PrescriptionOrderRepository(TenantBaseRepository[PrescriptionOrder]):
    model = PrescriptionOrder

    async def get_by_code(self, tenant_id: UUID, code: str) -> PrescriptionOrder | None:
        stmt = select(PrescriptionOrder).where(
            PrescriptionOrder.tenant_id == tenant_id,
            PrescriptionOrder.code == code,
            PrescriptionOrder.is_deleted.is_(False),
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()


class PrescriptionLineRepository(TenantBaseRepository[PrescriptionLine]):
    model = PrescriptionLine

    async def list_by_order(self, tenant_id: UUID, prescription_order_id: UUID):
        stmt = select(PrescriptionLine).where(
            PrescriptionLine.tenant_id == tenant_id,
            PrescriptionLine.prescription_order_id == prescription_order_id,
            PrescriptionLine.is_deleted.is_(False),
        )
        result = await self.session.execute(stmt)
        return result.scalars().all()


class PrescriptionStatusHistoryRepository(TenantBaseRepository[PrescriptionStatusHistory]):
    model = PrescriptionStatusHistory
