#!/usr/bin/env node

import fs from 'node:fs';
import path from 'node:path';
import { CredentialVault } from '../apps/gateway/src/core/credential-vault.js';
import { resolveMasterKey } from '@zyphon/crypto';

/**
 * Re-encrypts the vault file with a new master key.
 * Usage: node scripts/rotate-secrets.js <new_32_byte_hex_key> [vault_path]
 */
async function main() {
  const args = process.argv.slice(2);
  const newKeyHex = args[0] || process.env.NEW_ZYPHON_MASTER_KEY;
  const vaultPath = args[1] || process.env.ZYPHON_VAULT_PATH || './data/state/vault.enc.json';

  if (!newKeyHex) {
    console.error(`Usage: node scripts/rotate-secrets.js <new_32_byte_hex_key> [vault_path]`);
    console.error(`Or set NEW_ZYPHON_MASTER_KEY in environment.`);
    process.exit(1);
  }

  const resolvedPath = path.resolve(vaultPath);
  if (!fs.existsSync(resolvedPath)) {
    console.error(`Vault file not found at: ${resolvedPath}`);
    process.exit(1);
  }

  console.log(`[Vault Key Rotation] Target vault: ${resolvedPath}`);
  const currentMasterKey = resolveMasterKey();
  const newMasterKey = resolveMasterKey(newKeyHex);

  const vault = new CredentialVault(resolvedPath, currentMasterKey);
  const statsBefore = vault.getStats();
  console.log(`[Vault Key Rotation] Current vault contains ${statsBefore.providersCount} provider secrets.`);

  vault.reEncryptWithNewKey(newMasterKey);
  console.log(`✓ Vault successfully re-encrypted with new master key!`);
  console.log(`  Atomic write completed with mode 0600 and backup preserved.`);
  console.log(`  Remember to update ZYPHON_MASTER_KEY in your environment to the new key.`);
}

main().catch((err) => {
  console.error('Fatal rotation error:', err);
  process.exit(1);
});

