import { Client } from "basic-ftp";

export default async function uploadFilesInBatch(
  files: string[],
  errores?: string[],
  dict?: Dictionary,
) {
  const uploadPromises: Promise<void>[] = [];

  for (const file of files) {
    uploadPromises.push(
      new Promise(async (resolve, reject) => {
        const client = new Client();
        try {
          await client.access({
            host: process.env.CPANEL_FTP_HOST,
            user: process.env.CPANEL_USER,
            password: process.env.CPANEL_PASS,
          });
          client.ftp.verbose = true;

          const splitted = file.split("/");
          const detectFolder = splitted.findIndex((e) =>
            e.includes("FEDSITE_"),
          );
          const fileJoined = splitted.slice(detectFolder).join("/");
          const fileFolder = fileJoined.slice(0, fileJoined.lastIndexOf("/"));

          await client.ensureDir(fileFolder);
          await client.cd("/");
          await client.uploadFrom(file, splitted.slice(detectFolder).join("/"));
          client.close();
          resolve();
        } catch (err: any) {
          errores?.push(
            `${dict.alerts.general.error_uploading} ${file}: ${err.message}`,
          );
          client.close();
          reject();
        }
      }),
    );
  }

  await Promise.all(uploadPromises);
}
