const fs = require("fs");
const path = require("path");

const processData = process.argv;
console.log("processData", processData);
const filePath = processData[2] ? `../pages/${processData[2]}` : `../pages`;
const pageDir = path.resolve(__dirname, filePath);
const routePath = path.resolve(__dirname, "../routes/LazyLoad.js");
// console.log("__dirname", path.resolve(__dirname, "../pages"));

const generateLazyPages = () => {
  const directoryContent = fs.readdirSync(pageDir);
  //   console.log("directoryContent >>", directoryContent);
  if (directoryContent.length) {
    const exportedPages = directoryContent.map((item) => {
      if (item.endsWith(".jsx")) {
        return `
            export const ${item.replace(".jsx", "")} = lazy(() => {
                const __import = import("${filePath}/${item.replace(
          ".jsx",
          ""
        )}");
                __import.finally(() => {});
                return __import;
              });
            `;
      }
    });
    const result = fs.appendFileSync(routePath, exportedPages.join("\n"));
    console.log("result >>", result);
  }
};

generateLazyPages();
