import { createCipheriv, createDecipheriv, createHash, randomBytes, scryptSync } from 'node:crypto';
import { Api } from '@mondaydotcomorg/trident-backend-api';

/**
 * Symmetric encryption for secrets at rest. AES-256-GCM with a key derived
 * (via scrypt, salted per blob) from the `z2h_secrets_key` secret. The `v1:`
 * prefix leaves room to rotate the scheme without breaking stored blobs.
 * Decryption happens server-side only, and a decrypted value never crosses
 * into an isolate.
 *
 * Shared between `bigbrain-zth` (encrypts on write) and `zth-backend-runner`
 * (decrypts on use) — both must read the *same* `z2h_secrets_key` value, so
 * this must stay byte-identical across the two callers.
 */

/** Config-variables key (how mm + the cluster inject it), stored as {"key":"…"}. */
const KEY_CONFIG = 'z2h_secrets_key';
const CURRENT_VERSION = 'v1' as const;
const SALT_LENGTH = 16;
const SCRYPT_KEY_LENGTH = 32;
/** Full-length GCM tag. Enforced on decrypt so a truncated tag can't weaken the
 * forgery margin (a short tag shrinks it from 2^128 toward 2^32). */
const GCM_TAG_LENGTH = 16;
/** Bounds the derived-key cache below — one entry per distinct (passphrase,
 * salt) pair ever seen, so a long-lived process can't grow this unbounded. */
const MAX_CACHED_KEYS = 256;

/**
 * The passphrase from the trident `configurationVariables` secret, a
 * `{ key: "…" }` object.
 */
function passphraseSource(): string | undefined {
  const cfg = Api.getPart('configurationVariables')?.get(KEY_CONFIG) as { key?: string } | undefined;
  return cfg?.key || undefined;
}

function passphrase(): string {
  const configured = passphraseSource();
  if (!configured) {
    throw new Error(`${KEY_CONFIG} must be set`);
  }
  return configured;
}

// Each blob carries its own random salt (see encryptSecret), so the key derived
// for it is cached by (passphrase, salt) rather than by passphrase alone — a
// repeated read of the same still-live blob skips re-running scrypt.
const derivedKeyCache = new Map<string, Buffer>();

function deriveKey(source: string, salt: Buffer): Buffer {
  // Hash the passphrase for the cache key so the plaintext secret isn't held
  // in memory for the cache's lifetime (rather than just for this call).
  const sourceDigest = createHash('sha256').update(source).digest('base64');
  const cacheKey = `${sourceDigest}:${salt.toString('base64')}`;
  const cached = derivedKeyCache.get(cacheKey);
  if (cached) {
    return cached;
  }
  const derived = scryptSync(source, salt, SCRYPT_KEY_LENGTH);
  if (derivedKeyCache.size >= MAX_CACHED_KEYS) {
    const oldest = derivedKeyCache.keys().next().value;
    if (oldest !== undefined) {
      derivedKeyCache.delete(oldest);
    }
  }
  derivedKeyCache.set(cacheKey, derived);
  return derived;
}

export function encryptSecret(plaintext: string): string {
  const salt = randomBytes(SALT_LENGTH);
  const iv = randomBytes(12);
  const cipher = createCipheriv('aes-256-gcm', deriveKey(passphrase(), salt), iv);
  const enc = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
  const tag = cipher.getAuthTag();
  return [
    CURRENT_VERSION,
    iv.toString('base64'),
    salt.toString('base64'),
    tag.toString('base64'),
    enc.toString('base64'),
  ].join(':');
}

export function decryptSecret(blob: string): string {
  const parts = blob.split(':');
  if (parts.length !== 5) {
    throw new Error('unrecognized secret format');
  }
  const [version, ivB64, saltB64, tagB64, dataB64] = parts;
  if (version !== CURRENT_VERSION || !ivB64 || !saltB64 || !tagB64 || dataB64 === undefined) {
    throw new Error('unrecognized secret format');
  }
  const tag = Buffer.from(tagB64, 'base64');
  if (tag.length !== GCM_TAG_LENGTH) {
    throw new Error('unrecognized secret format');
  }
  const key = deriveKey(passphrase(), Buffer.from(saltB64, 'base64'));
  const decipher = createDecipheriv('aes-256-gcm', key, Buffer.from(ivB64, 'base64'), {
    authTagLength: GCM_TAG_LENGTH,
  });
  decipher.setAuthTag(tag);
  return Buffer.concat([decipher.update(Buffer.from(dataB64, 'base64')), decipher.final()]).toString('utf8');
}
