import { writeFile, mkdir } from "fs/promises";
import path from "path";
import { NextResponse } from "next/server";

export const POST = async (req) => {
  try {
    const formData = await req.formData();
    const file = formData.get("file");
    const locationName = formData.get("locationName") || "default";
    const getFileName = formData.get("fileName") || "default";

    if (!file) {
      return NextResponse.json({ error: "No file uploaded" }, { status: 400 });
    }

    const buffer = Buffer.from(await file.arrayBuffer());
    const fileName = getFileName;

    const dirPath = path.join(process.cwd(), "uploads", locationName);
    const uploadPath = path.join(dirPath, fileName);

    await mkdir(dirPath, { recursive: true });
    await writeFile(uploadPath, buffer);

    // Serve it via your API route: /api/files/...
    return NextResponse.json({
      url: `/api/files/${locationName}/${fileName}`,
    });
  } catch (err) {
    console.error("Upload error:", err);
    return NextResponse.json({ error: "Upload failed" }, { status: 500 });
  }
};
