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

export const SITE_TAG_ACTIVE_WINDOW_DAYS = 7;

export async function isSiteTagActive(brandId: string): Promise<boolean> {
  const cutoff = new Date(Date.now() - SITE_TAG_ACTIVE_WINDOW_DAYS * 24 * 60 * 60 * 1000);
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    select: { trackedSite: { select: { id: true } } },
  });
  if (!brand?.trackedSite) return false;
  const count = await prisma.trackedEvent.count({
    where: { trackedSiteId: brand.trackedSite.id, timestamp: { gte: cutoff } },
  });
  return count > 0;
}

export async function getActiveSiteTagBrandIds(brandIds: string[]): Promise<Set<string>> {
  if (brandIds.length === 0) return new Set();
  const cutoff = new Date(Date.now() - SITE_TAG_ACTIVE_WINDOW_DAYS * 24 * 60 * 60 * 1000);
  const brands = await prisma.brand.findMany({
    where: { id: { in: brandIds } },
    select: { id: true, trackedSite: { select: { id: true } } },
  });
  const siteIdToBrandId = new Map<string, string>();
  const trackedSiteIds: string[] = [];
  for (const b of brands) {
    if (b.trackedSite) {
      siteIdToBrandId.set(b.trackedSite.id, b.id);
      trackedSiteIds.push(b.trackedSite.id);
    }
  }
  if (trackedSiteIds.length === 0) return new Set();
  const activeSites = await prisma.trackedEvent.groupBy({
    by: ["trackedSiteId"],
    where: { trackedSiteId: { in: trackedSiteIds }, timestamp: { gte: cutoff } },
    _count: { _all: true },
  });
  const activeSet = new Set<string>();
  for (const s of activeSites) {
    const brandId = siteIdToBrandId.get(s.trackedSiteId);
    if (brandId) activeSet.add(brandId);
  }
  return activeSet;
}
