import crypto from 'node:crypto';
import { config } from '../config.js';

function keyBuffer() {
  // Derive fixed-length AES key material from the configured secret-like environment value.
  return crypto.createHash('sha256').update(config.credentialStoreKey).digest();
}

export function encryptSecret(value = '') {
  // AES-GCM stores cipher text plus IV/tag so reads can expose metadata without returning secrets.
  const iv = crypto.randomBytes(12);
  const cipher = crypto.createCipheriv('aes-256-gcm', keyBuffer(), iv);
  const encrypted = Buffer.concat([cipher.update(String(value), 'utf8'), cipher.final()]);
  const tag = cipher.getAuthTag();
  return {
    cipher: encrypted.toString('base64'),
    iv: iv.toString('base64'),
    tag: tag.toString('base64')
  };
}

export function decryptSecret(record) {
  // Missing cipher fields mean the credential has no retrievable secret rather than throwing.
  if (!record?.secret_cipher || !record?.secret_iv || !record?.secret_tag) return '';
  const decipher = crypto.createDecipheriv(
    'aes-256-gcm',
    keyBuffer(),
    Buffer.from(record.secret_iv, 'base64')
  );
  decipher.setAuthTag(Buffer.from(record.secret_tag, 'base64'));
  return Buffer.concat([
    decipher.update(Buffer.from(record.secret_cipher, 'base64')),
    decipher.final()
  ]).toString('utf8');
}
