"""Connector repositories — Phase 12.7."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select

from app.models.connectors import ConnectorDispatch, ConnectorRegistration
from app.repositories.base import TenantBaseRepository


class ConnectorRegistrationRepository(TenantBaseRepository[ConnectorRegistration]):
    model = ConnectorRegistration

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


class ConnectorDispatchRepository(TenantBaseRepository[ConnectorDispatch]):
    model = ConnectorDispatch

    async def list_for_registration(
        self, tenant_id: UUID, registration_id: UUID, *, offset: int, limit: int
    ) -> list[ConnectorDispatch]:
        stmt = (
            select(ConnectorDispatch)
            .where(
                ConnectorDispatch.tenant_id == tenant_id,
                ConnectorDispatch.registration_id == registration_id,
                ConnectorDispatch.is_deleted.is_(False),
            )
            .offset(offset)
            .limit(limit)
        )
        result = await self.session.execute(stmt)
        return list(result.scalars().all())
