from __future__ import annotations

import logging
from datetime import datetime, timedelta, timezone

from sqlalchemy import delete, text

from ..db import AsyncSessionLocal
from ..models import SaaSEvent

log = logging.getLogger(__name__)


async def refresh_saas_event_rollup() -> None:
    """Refresh materialized view used by SaaS event dashboards."""
    async with AsyncSessionLocal() as session:
        dialect = getattr(session.bind, "dialect", None)
        if not dialect or dialect.name != "postgresql":
            return
        try:
            await session.execute(
                text("REFRESH MATERIALIZED VIEW CONCURRENTLY saas_event_daily")
            )
            await session.commit()
            log.info("Refreshed saas_event_daily materialized view")
        except Exception:
            await session.rollback()
            log.exception("Failed to refresh saas_event_daily materialized view")


async def purge_old_saas_events(retention_days: int = 180) -> None:
    """Purge historical SaaS events beyond retention policy."""
    cutoff = datetime.now(timezone.utc) - timedelta(days=max(1, retention_days))
    async with AsyncSessionLocal() as session:
        try:
            await session.execute(delete(SaaSEvent).where(SaaSEvent.ts < cutoff))
            await session.commit()
            log.info(
                "Purged SaaS events older than %s days (cutoff=%s)",
                retention_days,
                cutoff.isoformat(),
            )
        except Exception:
            await session.rollback()
            log.exception("Failed to purge historical SaaS events")
