import { NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { sharePointScannerService } from "@/lib/services/sharePointScannerService";

export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const auth = await getServerSession(authOptions);
    if (!auth?.user) return NextResponse.json({ error: "No autenticado" }, { status: 401 });
    const { id } = await params;
    const body = await request.json().catch(() => ({})) as { duplicatesOnly?: boolean };
    const result = body.duplicatesOnly
      ? await sharePointScannerService.discardDuplicateFiles(id, auth.user.id, auth.user.role)
      : await sharePointScannerService.discardUnsavedFiles(id, auth.user.id, auth.user.role);
    return NextResponse.json({ success: true, ...result });
  } catch (error) {
    const message = error instanceof Error ? error.message : "No se pudieron cancelar los resultados.";
    return NextResponse.json({ error: message }, { status: message.includes("permisos") ? 403 : 422 });
  }
}
