const argumentsList = process.argv.slice(2);
if (argumentsList[0] === "--") argumentsList.shift();
const [expectedVersion, expectedKvNamespace] = argumentsList;
if (!expectedVersion || !expectedKvNamespace) {
  throw new Error(
    "Usage: node scripts/check-version-bindings.mjs <expected-version-id> <expected-kv-namespace-id>");
}

let input = "";
for await (const chunk of process.stdin) input += chunk;

let version;
try { version = JSON.parse(input); }
catch { throw new Error("Wrangler version details did not contain valid JSON."); }

if (version?.id !== expectedVersion || !Array.isArray(version?.resources?.bindings)) {
  throw new Error("Wrangler did not return the expected Worker version details.");
}
const bindings = version.resources.bindings;
const exactlyOne = (name, predicate) =>
  bindings.filter(binding => binding?.name === name && predicate(binding)).length === 1;

if (!exactlyOne("LICENSE_STATE", binding =>
  binding.type === "kv_namespace" && binding.namespace_id === expectedKvNamespace)) {
  throw new Error("The candidate is not bound to the expected licence-state namespace.");
}
if (!exactlyOne("CF_VERSION_METADATA", binding => binding.type === "version_metadata")) {
  throw new Error("The candidate is missing its Worker version-metadata binding.");
}
for (const secretName of ["SMARTCUT_PRIVATE_KEY_PEM", "LEMON_WEBHOOK_SECRET"]) {
  if (!exactlyOne(secretName, binding => binding.type === "secret_text")) {
    throw new Error(`The candidate is missing required secret binding ${secretName}.`);
  }
}

console.log(`SmartCut64 licensing version ${expectedVersion} has the expected critical bindings.`);
