/**
 * One-shot NATS test credential generator for the resilience test harness.
 *
 * Run with:
 *   bun run tests/resilience/scripts/gen-nats-creds.ts
 *
 * Outputs:
 *   tests/resilience/nats-config/nats.conf   — NATS server config (operator mode)
 *   tests/resilience/nats-config/cluster.creds — Studio cluster-auth credentials
 *
 * Also prints the NATS_ACCOUNT_JWT and NATS_ACCOUNT_SIGNING_KEY values that
 * must be pasted into docker-compose.yml's studio environment block.
 *
 * THESE ARE TEST-ONLY CREDENTIALS — no external trust chain, no production
 * access. Safe to commit; they only grant access to the local test NATS
 * container, which is never exposed outside the Docker network.
 */
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import {
  buildNatsOperatorArtifacts,
  generateNatsOperatorKeys,
} from "../../../apps/api/src/services/nats-operator-config";

const OUT = join(import.meta.dir, "..", "nats-config");
mkdirSync(OUT, { recursive: true });

const keys = generateNatsOperatorKeys();
const a = await buildNatsOperatorArtifacts(keys);

const conf = `# TEST-ONLY NATS operator config for resilience tests.
# Generated by tests/resilience/scripts/gen-nats-creds.ts — do not edit by hand.
# Re-run the script and recommit if you need to rotate these test credentials.

listen: 0.0.0.0:4222

operator: ${a.operatorJwt}
system_account: ${a.systemAccountPublicKey}

resolver: MEMORY
resolver_preload: {
  ${a.systemAccountPublicKey}: ${a.systemAccountJwt}
  ${a.tunnelAccountPublicKey}: ${a.tunnelAccountJwt}
}

jetstream {
  store_dir: "/tmp/nats-jetstream"
}

http: 8222

websocket {
  port: 4224
  no_tls: true
}
`;

writeFileSync(join(OUT, "nats.conf"), conf);
writeFileSync(join(OUT, "cluster.creds"), a.clusterCreds);

console.log("=== Generated ===");
console.log(`nats-config/nats.conf written`);
console.log(`nats-config/cluster.creds written`);
console.log("");
console.log("Paste these into docker-compose.yml under studio: environment:");
console.log(`  NATS_ACCOUNT_JWT: ${a.tunnelAccountJwt}`);
console.log(`  NATS_ACCOUNT_SIGNING_KEY: ${a.tunnelSigningSeed}`);
