/**
 * GET /api/conversion-intelligence?brandId=xxx&range=30d&compare=previous
 * Returns conversion data gated behind real connected integrations.
 *
 * Auto-refresh: when GA4 data is stale (>8h since last sync), triggers
 * a background sync for the brand before returning. Rate-limited to
 * one trigger per brand per 30 minutes via an in-memory throttle map.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getConversionIntelligence } from "@/lib/services/analytics-adapter";
import { triggerGa4RefreshIfStale } from "@/lib/services/ga4-freshness";
import type { DateRange, CompareMode } from "@/lib/services/date-utils";

export const dynamic = "force-dynamic";

export async function GET(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const { searchParams } = new URL(req.url);
  const brandId = searchParams.get("brandId");
  if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });
  if (!brand || !brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const range = (searchParams.get("range") ?? "30d") as DateRange;
  const compare = (searchParams.get("compare") ?? "previous") as CompareMode;

  // Stale-while-revalidate: return current data immediately, trigger
  // background GA4 sync if data is older than 8 hours (fire-and-forget).
  triggerGa4RefreshIfStale(brandId).catch(() => {});

  const result = await getConversionIntelligence(brandId, range, compare);
  return NextResponse.json(result);
}
