import { readFileSync } from "node:fs";

import type { SecureConfigCandidate } from "./registration.js";

export function readSecureConfigCandidate(path: string): SecureConfigCandidate {
  const parsed = JSON.parse(readFileSync(path, "utf8")) as Record<string, unknown>;
  if (parsed.schema_version !== 1 || !Number.isSafeInteger(parsed.secure_config_revision)) {
    throw new Error("secure_config_integrity_invalid");
  }
  if (!Array.isArray(parsed.admin_allowlist_hashes) || !Array.isArray(parsed.admin_recovery_hashes)) {
    throw new Error("secure_config_integrity_invalid");
  }
  if (parsed.admin_allowlist_hashes.some((value) => typeof value !== "string")
    || parsed.admin_recovery_hashes.some((value) => typeof value !== "string")) {
    throw new Error("secure_config_integrity_invalid");
  }
  return {
    adminAllowlistHashes: parsed.admin_allowlist_hashes as string[],
    adminRecoveryHashes: parsed.admin_recovery_hashes as string[],
    secureConfigRevision: parsed.secure_config_revision as number,
  };
}
