import fs from "node:fs";
import path from "node:path";

import { invokePowerShellScript } from "../powershell/invoke-script.js";

export async function unpackZip(zipPath, destinationRoot) {
  if (!fs.existsSync(destinationRoot)) {
    fs.mkdirSync(destinationRoot, { recursive: true });
  }

  const scriptPath = path.join(destinationRoot, "__expand-archive.ps1");
  fs.writeFileSync(
    scriptPath,
    `Expand-Archive -LiteralPath '${zipPath.replace(/'/g, "''")}' -DestinationPath '${destinationRoot.replace(/'/g, "''")}' -Force`,
    "utf8"
  );

  try {
    await invokePowerShellScript(scriptPath, [], { cwd: destinationRoot });
  } finally {
    if (fs.existsSync(scriptPath)) {
      fs.unlinkSync(scriptPath);
    }
  }
}
