import { NextRequest, NextResponse } from "next/server";
import { requireApiUser } from "@/lib/api-auth";
import { saveUploadedFile, type UploadFileType } from "@/lib/jobs/create-job";

export const maxDuration = 120;

export async function POST(req: NextRequest) {
  const { error, user } = await requireApiUser(req);
  if (error || !user) return error!;

  const formData = await req.formData();
  const file = formData.get("file") as File | null;
  const type = formData.get("type") as string | null;

  if (
    !file ||
    !type ||
    (type !== "image" && type !== "audio" && type !== "logo" && type !== "font")
  ) {
    return NextResponse.json(
      { error: "Provide multipart fields: file, type (image|audio|logo|font)" },
      { status: 400 },
    );
  }

  try {
    const result = await saveUploadedFile(user.id, file, type as UploadFileType);
    return NextResponse.json(result);
  } catch (err) {
    const message = err instanceof Error ? err.message : "Upload failed";
    return NextResponse.json({ error: message }, { status: 400 });
  }
}
