import unzipFile from "@/services/unzipp";
import uploadFolders from "@/services/uploadFolders";
import { copyFile, mkdir, readFile, rename, rm, writeFile } from "fs/promises";
import { join } from "path";

export async function processFiles(
  local: string,
  template: string,
  subdomain: string,
  certs: any[],
  version: string,
) {
  const file = new File([await readFile(local)], "site.zip");
  const targetDir = local.slice(0, local.lastIndexOf("/"));
  const folderName = `/FEDSITE_${subdomain}`;

  await unzipFile(file, targetDir, {
    isAuth: false,
  });

  await rm(local);

  await writeFile(targetDir + `/${version}/assets/js/data.js`, template);

  await rename(targetDir + `/${version}`, targetDir + folderName);

  if (certs.length > 0) {
    await mkdir(
      join(targetDir, folderName, "assets", "images", "certificates"),
      {
        recursive: true,
      },
    );

    for (const cert of certs) {
      await copyFile(
        join("public", "certificates", cert.src),
        join(
          targetDir,
          folderName,
          "assets",
          "images",
          "certificates",
          cert.src,
        ),
      );
    }
  }

  await uploadFolders(targetDir);
}
