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

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 [summary, platforms, sessions] = await Promise.all([
    getChannelSummary(brandId, since),
    getAdPlatformStatus(brandId),
    getSessionCount(brandId, since),
  ]);

  const rate = sessions > 0 ? Math.round((summary.totalConversions / sessions) * 1000) / 10 : 0;

  return NextResponse.json({
    paidChannels: {
      totalSessions: summary.paid.sessions,
      totalConversions: summary.paid.conversions,
      spend: summary.paid.spend,
      roas: summary.paid.roas,
      cpc: summary.paid.cpc,
      cpl: summary.paid.cpl,
      channels: Object.entries(summary.paid.byChannel).map(([ch, d]) => ({ channel: ch, ...d })),
    },
    organicChannels: {
      totalSessions: summary.organic.sessions,
      totalConversions: summary.organic.conversions,
      channels: Object.entries(summary.organic.byChannel).map(([ch, d]) => ({ channel: ch, ...d })),
    },
    assistedConversions: summary.assisted,
    totals: {
      sessions,
      conversions: summary.totalConversions,
      conversionRate: rate,
      paidShareOfConversions: summary.paidShareOfConversions,
      organicShareOfConversions: summary.organicShareOfConversions,
      assistedShareOfConversions: summary.assistedShareOfConversions,
    },
    platforms,
    channelBackfillTriggered: summary.channelBackfillTriggered,
  });
}
