import { Handlers } from "$fresh/server.ts";
import { ensureFile } from "$std/fs/ensure_file.ts";

export const handler: Handlers = {
  async POST(req, _ctx) {
    const path = req.headers.get("x-grizz-path");
    if (!path) return new Response("Upload path not included", { status: 400 });

    const files = Array.from((await req.formData()).values()) as File[];

    for (const file of files) {
      const filePath = path.replace(/.$/, (e) => e.replace("/", "") + "/") +
        file.name;
      await ensureFile(filePath);
      const newFile = await Deno.open(filePath, { write: true });
      file.stream().pipeTo(newFile.writable);
    }

    return new Response("Success");
  },
};
