import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getAdPlatformStatus, getPaidChannelMetrics } from "@/lib/services/paid-media-metrics";
import { planHasFeature, resolveEffectivePlan } from "@/lib/plan-config";
import type { PlanId } from "@/lib/plan-config";

export const dynamic = "force-dynamic";
export const maxDuration = 30;

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 effectivePlan = resolveEffectivePlan({ plan: (brand.plan as PlanId) ?? "trial", planExpiresAt: brand.planExpiresAt });
  if (!planHasFeature({ plan: effectivePlan }, "paid_media")) {
    return NextResponse.json({ error: "Paid Media requires an Agency plan or higher", requiredPlan: "agency" }, { status: 403 });
  }

  const days = parseInt(searchParams.get("range") ?? "28d") || 28;
  const since = new Date(Date.now() - days * 86_400_000);
  const platforms = await getAdPlatformStatus(brandId);

  if (platforms.connected.length === 0) {
    return NextResponse.json({
      connected: false,
      message: "Connect an ad platform to compare their claimed conversions against what the Site Tag actually measured on your site.",
      platforms,
      overallClaimed: 0,
      overallVerified: 0,
      overallDiscrepancy: 0,
      byPlatform: [],
      topDiscrepancyCampaigns: [],
    });
  }

  const [campaignRows, paidMetrics] = await Promise.all([
    prisma.adCampaignData.findMany({
      where: { brandId, date: { gte: since } },
      select: { platform: true, campaignName: true, campaignId: true, platformConversions: true },
    }).catch(() => []),
    getPaidChannelMetrics(brandId, since),
  ]);

  const byPlatformMap = new Map<string, { claimed: number; verified: number }>();
  for (const r of campaignRows) {
    const e = byPlatformMap.get(r.platform) ?? { claimed: 0, verified: 0 };
    e.claimed += r.platformConversions;
    byPlatformMap.set(r.platform, e);
  }
  for (const [, e] of byPlatformMap) {
    e.verified = paidMetrics.conversions;
  }

  let overallClaimed = 0;
  const byPlatform = [...byPlatformMap.entries()].map(([platform, d]) => {
    overallClaimed += d.claimed;
    const disc = d.claimed - d.verified;
    return {
      platform,
      platformClaimed: d.claimed,
      siteTagVerified: d.verified,
      discrepancy: disc,
      discrepancyPct: d.claimed > 0 ? Math.round((disc / d.claimed) * 100) : 0,
    };
  });

  const overallVerified = paidMetrics.conversions;
  const overallDiscrepancy = overallClaimed - overallVerified;

  return NextResponse.json({
    connected: true,
    platforms,
    overallClaimed,
    overallVerified,
    overallDiscrepancy,
    byPlatform,
    topDiscrepancyCampaigns: [],
  });
}
