import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getAdPlatformStatus } 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 Google Ads, Meta, or another ad platform in Settings → Integrations to see campaign performance data.",
      platforms,
      summary: { totalCampaigns: 0, totalSpend: 0, totalClicks: 0, totalImpressions: 0 },
      campaigns: [],
    });
  }

  const rows = await prisma.adCampaignData.findMany({
    where: { brandId, date: { gte: since } },
  }).catch(() => []);

  const campAgg = new Map<string, {
    campaignName: string; platform: string;
    impressions: number; clicks: number; spend: number; platformConversions: number;
  }>();
  for (const r of rows) {
    const e = campAgg.get(r.campaignId) ?? {
      campaignName: r.campaignName, platform: r.platform,
      impressions: 0, clicks: 0, spend: 0, platformConversions: 0,
    };
    e.impressions += r.impressions;
    e.clicks += r.clicks;
    e.spend += r.spend;
    e.platformConversions += r.platformConversions;
    campAgg.set(r.campaignId, e);
  }

  const campaigns = [...campAgg.values()].sort((a, b) => b.spend - a.spend);
  const totalSpend = campaigns.reduce((s, c) => s + c.spend, 0);
  const totalClicks = campaigns.reduce((s, c) => s + c.clicks, 0);
  const totalImpressions = campaigns.reduce((s, c) => s + c.impressions, 0);

  return NextResponse.json({
    connected: true,
    platforms,
    summary: { totalCampaigns: campaigns.length, totalSpend, totalClicks, totalImpressions },
    campaigns,
  });
}
