import fs from "fs-extra";
import path from "path";
import { fileURLToPath } from "url";

// Get the current directory of the module
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const sourceDir = path.join(__dirname, "/");
const destDir = path.join("./", "dist", "server", "scripts");

// Copy only .ps1 files
fs.readdir(sourceDir)
  .then((files) => {
    files.forEach((file) => {
      if (path.extname(file) === ".ps1") {
        const sourceFile = path.join(sourceDir, file);
        const destFile = path.join(destDir, file);

        // Copy each .ps1 file
        fs.copy(sourceFile, destFile)
          .then(() => {
            console.log(`Copied: ${file}`);
          })
          .catch((err) => {
            console.error(`Error copying file: ${file}`, err);
          });
      }
    });
  })
  .catch((err) => {
    console.error("Error reading source directory:", err);
  });

// Paths for source and destination of serverData.json
const sourceFile = path.join(
  "./",
  "server",
  "services",
  "server",
  "utils",
  "serverData.json"
);
const serverDataDest = path.join(
  "./",
  "dist",
  "server",
  "services",
  "server",
  "utils"
);
const destFile = path.join(serverDataDest, "serverData.json");

// Ensure the destination directory exists
fs.ensureDir(destDir)
  .then(() => {
    // Copy the serverData.json file
    return fs.copy(sourceFile, destFile);
  })
  .then(() => {
    console.log("serverData.json copied successfully!");
  })
  .catch((err) => {
    console.error("Error copying serverData.json:", err);
  });
