from __future__ import annotations

from typing import Sequence
from uuid import UUID

from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from src.domain.integration_events.models import IntegrationSubscription, ProjectCustomEvent


class IntegrationEventsRepository:
    def __init__(self, db: AsyncSession) -> None:
        self._db = db

    async def list_subscriptions(self, project_id: UUID) -> Sequence[IntegrationSubscription]:
        res = await self._db.execute(
            select(IntegrationSubscription)
            .where(IntegrationSubscription.project_id == project_id)
            .order_by(IntegrationSubscription.created_at.desc())
        )
        return res.scalars().all()

    async def get_subscription(self, project_id: UUID, sub_id: UUID) -> IntegrationSubscription | None:
        res = await self._db.execute(
            select(IntegrationSubscription).where(
                IntegrationSubscription.id == sub_id,
                IntegrationSubscription.project_id == project_id,
            )
        )
        return res.scalar_one_or_none()

    async def add_subscription(self, row: IntegrationSubscription) -> IntegrationSubscription:
        self._db.add(row)
        await self._db.flush()
        return row

    async def delete_subscription(self, row: IntegrationSubscription) -> None:
        await self._db.delete(row)
        await self._db.flush()

    async def list_custom_events(self, project_id: UUID) -> Sequence[ProjectCustomEvent]:
        res = await self._db.execute(
            select(ProjectCustomEvent).where(ProjectCustomEvent.project_id == project_id)
        )
        return res.scalars().all()
