"""Repository مربوط به ServiceRegistry و رویدادها."""
from __future__ import annotations

from typing import Sequence

from sqlalchemy import select

from app.models.events import OutboxEvent
from app.models.registry import ServiceRegistry
from app.repositories.base import BaseRepository
from shared.events import EventStatus


class ServiceRegistryRepository(BaseRepository[ServiceRegistry]):
    model = ServiceRegistry

    async def get_by_key(self, service_key: str) -> ServiceRegistry | None:
        stmt = select(ServiceRegistry).where(
            ServiceRegistry.service_key == service_key
        )
        result = await self.session.execute(stmt)
        return result.scalar_one_or_none()


class OutboxRepository(BaseRepository[OutboxEvent]):
    model = OutboxEvent

    async def list_pending(self, limit: int = 100) -> Sequence[OutboxEvent]:
        stmt = (
            select(OutboxEvent)
            .where(OutboxEvent.status == EventStatus.PENDING)
            .order_by(OutboxEvent.created_at.asc())
            .limit(limit)
        )
        result = await self.session.execute(stmt)
        return result.scalars().all()
