import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getVisitorProfileSummary } 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 page = Math.max(0, parseInt(searchParams.get("page") ?? "0"));

  const [summary, visitors] = await Promise.all([
    getVisitorProfileSummary(brandId, since),
    prisma.visitorProfile.findMany({
      where: { brandId, lastSeenAt: { gte: since } },
      orderBy: { lastSeenAt: "desc" },
      take: 50,
      skip: page * 50,
    }).catch(() => []),
  ]);

  return NextResponse.json({ summary, visitors });
}
