/**
 * GET /api/competitors/[id]/changes?since=DATE — detailed change list.
 */

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, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const comp = await prisma.competitor.findUnique({
    where: { id: params.id },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!comp) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (!comp.brand.organization.memberships.some((m) => m.userId === user.id)) return NextResponse.json({ error: "Access denied" }, { status: 403 });

  const since = new Date(new URL(req.url).searchParams.get("since") || Date.now() - 30 * 86400000);
  const snapshots = await prisma.competitorSnapshot.findMany({
    where: { competitorId: params.id, crawledAt: { gte: since } },
    orderBy: { crawledAt: "desc" },
    select: { newPages: true, removedPages: true, crawledAt: true },
  });

  const allNew: string[] = []; const allRemoved: string[] = [];
  for (const s of snapshots) {
    if (Array.isArray(s.newPages)) allNew.push(...(s.newPages as string[]));
    if (Array.isArray(s.removedPages)) allRemoved.push(...(s.removedPages as string[]));
  }

  return NextResponse.json({ newPages: [...new Set(allNew)], removedPages: [...new Set(allRemoved)], snapshotCount: snapshots.length });
}
