"use server";
import fs from "node:fs/promises";
import { revalidatePath } from "next/cache";
import { auth } from "../auth";
import { hasPermission, Role } from "@/lib/validation/permissions";

export async function uploadFile(formData: FormData) {
  const session = await auth();

  if (!session || !hasPermission(session.user.role, Role.EDITOR)) return false;
  console.log("Starting upload");

  const file = formData.get("file") as File;
  const arrayBuffer = await file.arrayBuffer();
  const buffer = new Uint8Array(arrayBuffer);
  const filename = `upload-${Date.now()}-${file.name}.png`;
  console.log("Filename", filename);

  try {
    await fs.writeFile(`./public/uploads/${filename}`, buffer);
    console.log("File uploaded successfully");

    revalidatePath("/");

    return `/uploads/${filename}`;
  } catch (e) {
    console.error("Error uploading file:", e);
    return false;
  }
}
