import { createCipheriv, createDecipheriv, randomBytes } from 'crypto';

const ALGO = 'aes-256-gcm';

const getKey = () => {
  const key = process.env.DATA_ENCRYPTION_KEY;
  if (!key) throw new Error('DATA_ENCRYPTION_KEY is not set');

  const keyBuf = Buffer.from(key, 'base64');
  if (keyBuf.length !== 32) throw new Error('DATA_ENCRYPTION_KEY must be base64-encoded 32 bytes');
  return keyBuf;
};

export const encryptText = (plainText) => {
  const iv = randomBytes(12);
  const key = getKey();
  const cipher = createCipheriv(ALGO, key, iv);

  const encrypted = Buffer.concat([cipher.update(plainText, 'utf8'), cipher.final()]);
  const tag = cipher.getAuthTag();

  return `${iv.toString('base64')}:${tag.toString('base64')}:${encrypted.toString('base64')}`;
};

export const decryptText = (payload) => {
  const [ivB64, tagB64, dataB64] = payload.split(':');
  if (!ivB64 || !tagB64 || !dataB64) throw new Error('Invalid encrypted payload format');

  const key = getKey();
  const decipher = createDecipheriv(ALGO, key, Buffer.from(ivB64, 'base64'));
  decipher.setAuthTag(Buffer.from(tagB64, 'base64'));

  const decrypted = Buffer.concat([
    decipher.update(Buffer.from(dataB64, 'base64')),
    decipher.final()
  ]);

  return decrypted.toString('utf8');
};
