import { NextResponse } from "next/server";
import { callPortalBackend } from "@/lib/backend";

export const dynamic = "force-dynamic";

type RouteContext = { params: Promise<{ token: string }> };

type UploadBody = {
  fileName?: string;
  mimeType?: string;
  base64?: string;
  checklistItemId?: string;
  checklistLabel?: string;
};

const MAX_BASE64_LENGTH = 36_000_000;

export async function POST(request: Request, context: RouteContext) {
  try {
    const { token } = await context.params;
    if (!/^[a-f0-9]{40,64}$/i.test(token)) {
      return NextResponse.json({ ok: false, error: "Lien de dossier invalide." }, { status: 404 });
    }

    const body = (await request.json()) as UploadBody;
    if (!body.fileName || !body.mimeType || !body.base64 || !body.checklistItemId || !body.checklistLabel) {
      return NextResponse.json({ ok: false, error: "Dépôt incomplet." }, { status: 400 });
    }
    if (body.base64.length > MAX_BASE64_LENGTH) {
      return NextResponse.json({ ok: false, error: "Le fichier dépasse la taille maximale autorisée." }, { status: 413 });
    }

    const data = await callPortalBackend<unknown>({
      action: "upload_piece",
      token,
      upload: body,
    });
    return NextResponse.json({ ok: true, data });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Dépôt impossible.";
    return NextResponse.json({ ok: false, error: message }, { status: 502 });
  }
}

