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

export async function POST(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const auth = await getServerSession(authOptions);
    if (!auth?.user) return NextResponse.json({ error: "No autenticado" }, { status: 401 });
    const { fileId, extractedData } = await request.json() as { fileId?: string; extractedData?: Record<string, unknown> };
    if (!fileId || !extractedData || Array.isArray(extractedData)) return NextResponse.json({ error: "Archivo y datos extraídos son obligatorios." }, { status: 400 });
    const { id } = await params;
    const result = await sharePointScannerService.saveFile(id, fileId, extractedData, auth.user.id, auth.user.role);
    return NextResponse.json({ success: true, ...result });
  } catch (error) {
    const message = error instanceof Error ? error.message : "No se pudo guardar el documento.";
    if (error instanceof DuplicateDocumentError) {
      return NextResponse.json({ error: message, duplicateDocument: error.duplicate }, { status: 409 });
    }
    return NextResponse.json({ error: message }, { status: message.includes("permisos") ? 403 : 500 });
  }
}
