import axios from "axios";
import archiver from "archiver";
import errorTypeCheck from "../../util/errorTypeCheck";
import { UUID } from "crypto";
import fs from "fs";
import path from "path";
import stream from "stream";
import { getTokenFromRenderer } from "../graphql/graphql-client";
import store from "../store/store";

async function UploadEmsToS3({
  extensionlessFilePath,
  bodyshopid,
  clm_no,
  ciecaid,
  ownr_ln,
}: {
  extensionlessFilePath: string;
  bodyshopid: UUID;
  clm_no: string;
  ciecaid: string;
  ownr_ln: string;
}): Promise<boolean> {
  // This function is a placeholder for the actual upload logic
  try {
    const directory = path.dirname(extensionlessFilePath);
    const baseFilename = path.basename(extensionlessFilePath);

    // Find all files in the directory that start with the base filename
    const filesToZip = fs
      .readdirSync(directory)
      .filter((file) => file.startsWith(baseFilename))
      .map((file) => path.join(directory, file));

    if (filesToZip.length === 0) {
      console.error("No files found to zip.");
      return false;
    }

    // Create a zip archive in memory
    const archive = archiver("zip", { zlib: { level: 9 } });
    const zipBuffer = await new Promise<Buffer>((resolve, reject) => {
      const buffers: Buffer[] = [];
      const writableStream = new stream.Writable({
        write(chunk, _encoding, callback) {
          buffers.push(chunk);
          callback();
        },
      });

      writableStream.on("finish", () => resolve(Buffer.concat(buffers)));
      writableStream.on("error", reject);

      archive.pipe(writableStream);

      // Append files to the archive
      filesToZip.forEach((file) => {
        archive.file(file, { name: path.basename(file) });
      });

      archive.finalize();
    });

    // Get the presigned URL from the server
    const presignedUrlResponse = await axios.post(
      `${
        store.get("app.isTest")
          ? import.meta.env.VITE_API_TEST_URL
          : import.meta.env.VITE_API_URL
      }/emsupload`,
      {
        bodyshopid,
        ciecaid,
        clm_no,
        ownr_ln,
      },
      {
        headers: {
          Authorization: `Bearer ${await getTokenFromRenderer()}`,
        },
      },
    );

    const presignedUrl = presignedUrlResponse.data?.presignedUrl;
    if (!presignedUrl) {
      console.error("Failed to retrieve presigned URL.");
      return false;
    }

    // Upload the zip file to S3 using the presigned URL
    await axios.put(presignedUrl, zipBuffer, {
      headers: {
        "Content-Type": "application/zip",
      },
    });
  } catch (error) {
    console.error("Error uploading EMS to S3:", errorTypeCheck(error));
    return false;
  }

  return true; // Return true if the upload is successful
}

export default UploadEmsToS3;
