/**
 * GET /api/competitors/overview?brandId=X — aggregated landscape view.
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

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

  const competitors = await prisma.competitor.findMany({
    where: { brandId, isActive: true },
    include: { snapshots: { orderBy: { crawledAt: "desc" }, take: 1, select: { totalPages: true, newPages: true, crawledAt: true } } },
  });

  const brandPages = await prisma.pageRecord.count({ where: { brandId } });
  let totalCompPages = 0;
  let totalNewCompPages = 0;
  const compSummaries = competitors.map((c) => {
    const snap = c.snapshots[0];
    const pages = snap?.totalPages ?? 0;
    const newP = Array.isArray(snap?.newPages) ? (snap.newPages as string[]).length : 0;
    totalCompPages += pages;
    totalNewCompPages += newP;
    return { id: c.id, domain: c.domain, name: c.name, pages, newPages: newP, lastCrawled: snap?.crawledAt ?? null };
  });

  // Keywords where competitors outrank the brand
  const outranked = await prisma.competitorRanking.findMany({
    where: { competitor: { brandId, isActive: true }, position: { not: null, lte: 10 } },
    orderBy: { position: "asc" },
    take: 20,
    include: { competitor: { select: { domain: true } } },
  });

  return NextResponse.json({
    brandPages,
    totalCompetitorPages: totalCompPages,
    totalNewCompPages,
    competitorCount: competitors.length,
    competitors: compSummaries,
    outrankedKeywords: outranked.map((r) => ({ keyword: r.keyword, position: r.position, domain: r.competitor.domain })),
  });
}
