/* eslint-disable no-await-in-loop */
import fs from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { exec as _exec } from "node:child_process";

const exec = promisify(_exec);

// Publishing packages to the public registry requires approval from appsec
const PUBLIC_PACKAGE_WHITELIST = [
  "@simplybusiness/mobius-hooks",
  "@simplybusiness/icons",
  "@simplybusiness/mobius-datepicker",
  "@simplybusiness/mobius",
  "@simplybusiness/services",
  "@simplybusiness/theme-core",
  "@simplybusiness/theme-simplybusiness",
];

test("Doesn't add new publicly published packages without appsec approval", async () => {
  const { stdout } = await exec("yarn workspaces list --json");
  const packages = stdout
    .trim()
    .split("\n")
    .map(json => JSON.parse(json));

  // eslint-disable-next-line no-restricted-syntax
  for (const pkg of packages) {
    const packagePath = require.resolve(
      path.join("../../../", pkg.location, "package.json"),
    );
    const packageJson = JSON.parse(await fs.readFile(packagePath, "utf-8"));

    if (packageJson.simplyBusiness?.publishToPublicNpm === true) {
      expect(PUBLIC_PACKAGE_WHITELIST).toContain(packageJson.name);
    }
  }
}, 30_000); // Set timeout to 30 seconds
