/**
 * Site Tag Installation Status — shared utility.
 * Use this instead of ad-hoc TrackedSite queries to determine
 * whether the Site Tag is truly active for a brand.
 *
 * "installed" = snippet generated (TrackedSite record exists)
 * "hasAnyEvents" = at least 1 event received (tag actually on the site)
 * "active" = events received in the last 48 hours
 */

import { prisma } from "@/lib/prisma";

export interface SiteTagStatus {
  installed: boolean;
  active: boolean;
  hasAnyEvents: boolean;
  totalEvents: number;
  lastEventAt: Date | null;
}

const ACTIVE_WINDOW_MS = 48 * 60 * 60 * 1000; // 48 hours

export async function getSiteTagStatus(brandId: string): Promise<SiteTagStatus> {
  const site = await prisma.trackedSite.findFirst({
    where: { brandId },
    select: { id: true, lastEventAt: true },
  });

  if (!site) {
    return { installed: false, active: false, hasAnyEvents: false, totalEvents: 0, lastEventAt: null };
  }

  const active = site.lastEventAt
    ? (Date.now() - site.lastEventAt.getTime()) < ACTIVE_WINDOW_MS
    : false;

  // hasAnyEvents: use lastEventAt as a proxy — avoids an unbounded
  // TrackedEvent.count that scans 10M+ rows for high-volume brands (366K
  // events/day × 30+ days). lastEventAt is written on every ingest, so a
  // non-null value reliably means at least one event was received.
  const hasAnyEvents = !!site.lastEventAt;

  // totalEvents: derive from the 30d rollup sum (fast indexed read on
  // SiteTagDailyRollup). Falls back to a bounded today-only count when
  // no rollup rows exist yet (new brand, cron lag).
  let totalEvents = 0;
  try {
    const rollupRows = await prisma.siteTagDailyRollup.findMany({
      where: { brandId, date: { gte: new Date(Date.now() - 30 * 86_400_000) } },
      select: { eventCountsByType: true },
    });
    if (rollupRows.length > 0) {
      for (const row of rollupRows) {
        const ect = (row.eventCountsByType ?? {}) as Record<string, number>;
        totalEvents += Object.values(ect).reduce((a, b) => a + b, 0);
      }
    } else if (hasAnyEvents) {
      const todayStart = new Date();
      todayStart.setUTCHours(0, 0, 0, 0);
      totalEvents = await prisma.trackedEvent.count({
        where: { trackedSiteId: site.id, timestamp: { gte: todayStart } },
      });
    }
  } catch { /* totalEvents is best-effort; active and hasAnyEvents are the critical fields */ }

  return {
    installed: true,
    active,
    hasAnyEvents,
    totalEvents,
    lastEventAt: site.lastEventAt,
  };
}
