"""Patient portal repositories — Phase 13.4."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select

from app.models.patient_portal import (
    PatientDocumentRef,
    PatientNotificationPreference,
    PatientPortalProfile,
)
from app.repositories.base import TenantBaseRepository


class PatientPortalProfileRepository(TenantBaseRepository[PatientPortalProfile]):
    model = PatientPortalProfile

    async def get_by_patient(self, tenant_id: UUID, patient_id: UUID) -> PatientPortalProfile | None:
        stmt = select(PatientPortalProfile).where(
            PatientPortalProfile.tenant_id == tenant_id,
            PatientPortalProfile.patient_id == patient_id,
            PatientPortalProfile.is_deleted.is_(False),
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()


class PatientDocumentRefRepository(TenantBaseRepository[PatientDocumentRef]):
    model = PatientDocumentRef

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

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


class PatientNotificationPreferenceRepository(TenantBaseRepository[PatientNotificationPreference]):
    model = PatientNotificationPreference

    async def get_pref(
        self, tenant_id: UUID, patient_id: UUID, channel: str, template_key: str
    ) -> PatientNotificationPreference | None:
        stmt = select(PatientNotificationPreference).where(
            PatientNotificationPreference.tenant_id == tenant_id,
            PatientNotificationPreference.patient_id == patient_id,
            PatientNotificationPreference.channel == channel,
            PatientNotificationPreference.template_key == template_key,
            PatientNotificationPreference.is_deleted.is_(False),
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()

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