"use server";

import { ServerResponse } from "@/lib/actions";
import { getCpanelVars } from "@/models/cpanel";
import uploadFolders from "@/services/uploadFolders";
import { mkdir, rm, writeFile } from "fs/promises";
import { v4 } from "uuid";
import { ServerAction } from "@/lib/actions";

export default async function updateFileContent(formData: FormData) {
  const { error, con, dict } = await ServerAction();

  if (error) {
    return ServerResponse({
      operation: false,
      data: error,
    });
  }

  const cpanel = getCpanelVars();

  const dir = formData.get("dir") as string;
  const file = formData.get("file") as string;
  const projectName = formData.get("project-name") as string;

  const tmp = v4();

  const errores: string[] = [];

  const tmpPath = `public/tmp/${tmp}`;

  const projectPath = `${tmpPath}/FEDSITE_${projectName}`;

  const fileName = dir.slice(
    `/home/${cpanel.user}/FEDSITE_${projectName}/`.length,
  );
  const filePath = fileName.split("/").slice(0, -1).join("/");

  try {
    await mkdir(`${projectPath}/${filePath}`, { recursive: true });

    await writeFile(`${projectPath}/${fileName}`, file, "utf8");

    await uploadFolders(tmpPath, errores, false);

    if (errores.length) {
      return ServerResponse({
        operation: false,
        message: errores.join("<br />"),
      });
    }

    return ServerResponse({
      operation: true,
      message: dict.alerts.save_file.success,
    });
  } catch (error) {
    return ServerResponse({
      operation: false,
      message: dict.alerts.general.unexpected_error,
      data: error,
    });
  } finally {
    con.release();
    await rm(tmpPath, { recursive: true });
  }
}
