import crypto from "crypto";
import { mkdirSync } from "fs";

const outputDir = "production-keys";

console.log(`
Generating Production Keys
-----------------
This script will generate all RSA key pairs needed for the production deployment.
Output directory: ${outputDir}/
-----------------`);

// Ensure output directory exists
mkdirSync(outputDir, { recursive: true });

const keyFiles = ["accessToken", "refreshToken", "permissions", "secureValues"];

const generatedKeys: Record<string, { private: string; public: string }> = {};

for (const name of keyFiles) {
  console.log(`Generating '${name}' key pair (4096-bit RSA)...`);
  const { privateKey, publicKey } = crypto.generateKeyPairSync("rsa", {
    modulusLength: 4096,
    privateKeyEncoding: { type: "pkcs8", format: "pem" },
    publicKeyEncoding: { type: "spki", format: "pem" },
  });
  generatedKeys[name] = { private: privateKey, public: publicKey };

  const privPath = `${outputDir}/${name}.key`;
  const pubPath = `${outputDir}/${name}.pub`;

  await Bun.write(privPath, privateKey);
  await Bun.write(pubPath, publicKey);

  console.log(`  ✔ ${privPath}`);
  console.log(`  ✔ ${pubPath}`);
}

// Generate Kubernetes Secret YAML
const toBase64 = (str: string) => Buffer.from(str).toString("base64");

const secretYaml = `apiVersion: v1
kind: Secret
metadata:
  name: optima-keys-secret
  namespace: optima
type: Opaque
data:
  ACCESS_TOKEN_PRIVATE_KEY: ${toBase64(generatedKeys["accessToken"].private)}
  REFRESH_TOKEN_PRIVATE_KEY: ${toBase64(generatedKeys["refreshToken"].private)}
  PERMISSIONS_PRIVATE_KEY: ${toBase64(generatedKeys["permissions"].private)}
  SECURE_VALUES_PRIVATE_KEY: ${toBase64(generatedKeys["secureValues"].private)}
  SECURE_VALUES_PUBLIC_KEY: ${toBase64(generatedKeys["secureValues"].public)}
`;

const secretPath = `${outputDir}/optima-keys-secret.yaml`;
await Bun.write(secretPath, secretYaml);
console.log(`\n  ✔ ${secretPath}`);

console.log(`
-----------------
All production keys and K8s Secret manifest generated in '${outputDir}/'.

⚠️  Delete the '${outputDir}/' directory after applying to your cluster.
    Do NOT commit these keys to version control.
-----------------
`);
