import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getAiVisibility, getAiVisibilityRecommendations, getAiVisibilitySummary } from "@/lib/services/ai-visibility";
import { DateRange, CompareMode } from "@/lib/services/date-utils";

/**
 * GET /api/ai-visibility?brandId=xxx&range=30d&compare=previous
 * GET /api/ai-visibility?brandId=xxx&summary=true
 * GET /api/ai-visibility?brandId=xxx&recommendations=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("summary") === "true") {
    const range = (searchParams.get("range") || "30d") as DateRange;
    const summary = await getAiVisibilitySummary(brandId, range);
    return NextResponse.json(summary);
  }

  if (searchParams.get("recommendations") === "true") {
    const recs = await getAiVisibilityRecommendations(brandId);
    return NextResponse.json(recs);
  }

  const range = (searchParams.get("range") || "30d") as DateRange;
  const compare = (searchParams.get("compare") || "previous") as CompareMode;
  const data = await getAiVisibility(brandId, range, compare);
  return NextResponse.json(data);
}
