import crypto from 'crypto';

const ALGORITHM = 'aes-256-cbc';
// Use process.env.ENCRYPTION_KEY or fallback to a default secure key
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || 'd6F3E0C1B2A3948576E5D4C3B2A10099'; // Must be 32 bytes
const IV_LENGTH = 16;

export function encrypt(text: string): string {
  if (!text) return '';
  const iv = crypto.randomBytes(IV_LENGTH);
  const cipher = crypto.createCipheriv(ALGORITHM, Buffer.from(ENCRYPTION_KEY), iv);
  let encrypted = cipher.update(text);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return iv.toString('hex') + ':' + encrypted.toString('hex');
}

export function decrypt(text: string): string {
  if (!text) return '';
  const textParts = text.split(':');
  const ivPart = textParts.shift();
  if (!ivPart) return '';
  const iv = Buffer.from(ivPart, 'hex');
  const encryptedText = Buffer.from(textParts.join(':'), 'hex');
  const decipher = crypto.createDecipheriv(ALGORITHM, Buffer.from(ENCRYPTION_KEY), iv);
  let decrypted = decipher.update(encryptedText);
  decrypted = Buffer.concat([decrypted, decipher.final()]);
  return decrypted.toString();
}

export function maskSecret(secret?: string | null): string {
  if (!secret) return '';
  return '************';
}
