/**
 * GET /api/ai-competitive-timeline?brandId=…&keyword=…
 *
 * Returns the competitive AI citation timeline showing position
 * changes over time for a brand's tracked keywords.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getCompetitiveTimeline } from "@/lib/intelligence/competitive-ai-alerts";

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 url = new URL(req.url);
  const brandId = url.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) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!brand.organization.memberships.some((m) => m.userId === user.id)) {
    return NextResponse.json({ error: "Access denied" }, { status: 403 });
  }

  const keyword = url.searchParams.get("keyword") ?? undefined;
  const limit = parseInt(url.searchParams.get("limit") ?? "30") || 30;

  const timeline = await getCompetitiveTimeline(brandId, keyword, limit);

  return NextResponse.json({ timeline });
}
