"""Delivery integration repositories — Phase 13.7."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select

from app.models.delivery_integration import (
    DeliveryIntegrationRegistration,
    DeliveryJobIntent,
    DeliveryJobStatusSnapshot,
)
from app.repositories.base import TenantBaseRepository


class DeliveryIntegrationRepository(TenantBaseRepository[DeliveryIntegrationRegistration]):
    model = DeliveryIntegrationRegistration

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


class DeliveryJobIntentRepository(TenantBaseRepository[DeliveryJobIntent]):
    model = DeliveryJobIntent

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

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

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


class DeliveryJobStatusSnapshotRepository(TenantBaseRepository[DeliveryJobStatusSnapshot]):
    model = DeliveryJobStatusSnapshot
