const path = require("path");

const { watch } = require("chokidar");

const nanoDevelopmentPlugin = () => {
  let restartTimeout;
  const isWatchMode = process.env.WATCH_MODE === "true";

  return {
    name: "vite-plugin-nano-development",
    configureServer(server) {
      const bigBinaryPackagesDir = path.resolve(
        process.cwd(),
        "node_modules",
        "@bigbinary"
      );

      watch(bigBinaryPackagesDir, { ignoreInitial: true })
        .on("add", restartServer)
        .on("change", restartServer)
        .on("error", error =>
          // eslint-disable-next-line no-console
          console.error(`[nano-development-plugin] watcher error: ${error}`)
        );

      function restartServer(filePath) {
        if (isWatchMode && !filePath.endsWith(".ready")) return;

        clearTimeout(restartTimeout);
        restartTimeout = setTimeout(async () => {
          try {
            await server.restart(true);
          } catch (error) {
            // eslint-disable-next-line no-console
            console.error(`[nano-development-plugin] restart error: ${error}`);
          }
        }, 300);
      }
    },
  };
};

module.exports = { nanoDevelopmentPlugin };
