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

/**
 * GET /api/conversions?brandId=xxx&range=30d&compare=previous
 *
 * Returns conversion intelligence data gated behind real connected sources.
 * No seed/demo data is returned.
 */
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");
  const range = (searchParams.get("range") || "30d") as DateRange;
  const compare = (searchParams.get("compare") || "previous") as CompareMode;

  if (!brandId) {
    return NextResponse.json({ error: "brandId is required" }, { status: 400 });
  }

  // Verify access
  const brand = await prisma.brand.findUnique({
    where: { id: brandId },
    include: { organization: { include: { memberships: true } } },
  });

  if (!brand) return NextResponse.json({ error: "Brand not found" }, { status: 404 });

  const isMember = brand.organization.memberships.some((m) => m.userId === user.id);
  if (!isMember) return NextResponse.json({ error: "Access denied" }, { status: 403 });

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