import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getRevenueAttribution, attributeConversions, getClosedLoopSummary, getAttributionBreakdown, AttributionModel } from "@/lib/services/revenue-attribution";
import { DateRange, CompareMode } from "@/lib/services/date-utils";

/**
 * GET /api/revenue-attribution?brandId=xxx&range=30d&model=last_touch
 * GET /api/revenue-attribution?brandId=xxx&breakdown=true
 * GET /api/revenue-attribution?brandId=xxx&closed_loop=true
 */
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");
  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 });
  }

  if (searchParams.get("breakdown") === "true") {
    const range = (searchParams.get("range") || "30d") as DateRange;
    const data = await getAttributionBreakdown(brandId, range);
    return NextResponse.json(data);
  }

  if (searchParams.get("closed_loop") === "true") {
    const range = (searchParams.get("range") || "30d") as DateRange;
    const summary = await getClosedLoopSummary(brandId, range);
    return NextResponse.json(summary);
  }

  const range = (searchParams.get("range") || "30d") as DateRange;
  const model = (searchParams.get("model") || "last_touch") as AttributionModel;
  const compare = (searchParams.get("compare") || "previous") as CompareMode;

  const data = await getRevenueAttribution(brandId, range, model, compare);
  return NextResponse.json(data);
}

/**
 * POST /api/revenue-attribution — run attribution for conversions
 * Body: { brandId, model? }
 */
export async function POST(req: Request) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  try {
    const { brandId, model } = await req.json();
    if (!brandId) return NextResponse.json({ error: "brandId required" }, { status: 400 });

    const result = await attributeConversions(brandId, model || "last_touch");
    return NextResponse.json(result);
  } catch {
    return NextResponse.json({ error: "Something went wrong" }, { status: 500 });
  }
}
