"""Analytics repositories — Phase 12.8."""
from __future__ import annotations

from uuid import UUID

from sqlalchemy import select

from app.models.analytics import AnalyticsReportDefinition, AnalyticsSnapshot
from app.repositories.base import TenantBaseRepository


class AnalyticsReportDefinitionRepository(TenantBaseRepository[AnalyticsReportDefinition]):
    model = AnalyticsReportDefinition

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


class AnalyticsSnapshotRepository(TenantBaseRepository[AnalyticsSnapshot]):
    model = AnalyticsSnapshot

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