/**
 * GET /api/competitors/[id]/snapshots — list snapshots over time.
 */

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 snapshots = await prisma.competitorSnapshot.findMany({
    where: { competitorId: params.id },
    orderBy: { crawledAt: "desc" },
    take: 20,
    select: { id: true, totalPages: true, newPages: true, removedPages: true, title: true, crawledAt: true },
  });

  return NextResponse.json({ snapshots });
}
