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

const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 16;

export function deriveAesKey(secret: string): Buffer {
  return createHash('sha256').update(secret).digest();
}

export function encryptAesGcm(data: Buffer, key: Buffer): { encrypted: Buffer; iv: Buffer; tag: Buffer } {
  const iv = randomBytes(IV_LENGTH);
  const cipher = createCipheriv(ALGORITHM, key, iv);
  const encrypted = Buffer.concat([cipher.update(data), cipher.final()]);
  const tag = cipher.getAuthTag();
  return { encrypted, iv, tag };
}

export function decryptAesGcm(encrypted: Buffer, iv: Buffer, tag: Buffer, key: Buffer): Buffer {
  const decipher = createDecipheriv(ALGORITHM, key, iv);
  decipher.setAuthTag(tag);
  return Buffer.concat([decipher.update(encrypted), decipher.final()]);
}

export function encryptStringAesGcm(text: string, key: Buffer): { encrypted: Buffer; iv: Buffer; tag: Buffer } {
  return encryptAesGcm(Buffer.from(text, 'utf-8'), key);
}

export function decryptToStringAesGcm(encrypted: Buffer, iv: Buffer, tag: Buffer, key: Buffer): string {
  return decryptAesGcm(encrypted, iv, tag, key).toString('utf-8');
}
