/**
 * GET /api/competitors/analysis?brandId=X[&competitorId=Y][&type=gaps|activity]
 *
 * Returns content gap analysis or recent activity for a brand's competitors.
 * type=gaps (default): content gaps + head-to-head comparisons
 * type=activity: recent new/updated/removed pages across all competitors
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { analyzeContentGaps, getRecentActivity } from "@/lib/services/competitor-analysis";

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");
  const competitorId = searchParams.get("competitorId") ?? undefined;
  const type = searchParams.get("type") ?? "gaps";

  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 });
  }

  try {
    if (type === "activity") {
      const days = parseInt(searchParams.get("days") ?? "30", 10);
      const activity = await getRecentActivity(brandId, days);
      return NextResponse.json({ activity });
    }

    const analysis = await analyzeContentGaps(brandId, competitorId);
    return NextResponse.json(analysis);
  } catch (err) {
    console.error("[competitors/analysis]", err);
    return NextResponse.json({ error: "Analysis failed" }, { status: 500 });
  }
}
