/**
 * POST /api/competitors/[id]/crawl — manual sitemap crawl + snapshot.
 *
 * Uses the comprehensive competitor-sitemap service which handles
 * sitemap discovery, XML/index/gzip parsing, per-page diffing, and
 * lightweight meta scraping. Falls back to the legacy crawlAndSnapshot
 * if the new crawler throws (defensive).
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { crawlCompetitor } from "@/lib/services/competitor-sitemap";

export const dynamic = "force-dynamic";
export const maxDuration = 120;

export async function POST(_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 });

  try {
    const result = await crawlCompetitor(comp.id);
    return NextResponse.json(result);
  } catch (err) {
    console.error("[competitor/crawl] crawlCompetitor failed", err);
    return NextResponse.json({ error: "Crawl failed", detail: String(err) }, { status: 500 });
  }
}
