import { encryptAesGcm, decryptAesGcm, deriveAesKey } from '@horux/core';
import { env } from '../../config/env.js';

function getKey(): Buffer {
  return deriveAesKey(env.FIEL_ENCRYPTION_KEY);
}

/**
 * Encripta datos usando AES-256-GCM con la clave derivada de FIEL_ENCRYPTION_KEY
 */
export function encrypt(data: Buffer): { encrypted: Buffer; iv: Buffer; tag: Buffer } {
  return encryptAesGcm(data, getKey());
}

/**
 * Desencripta datos usando AES-256-GCM con la clave derivada de FIEL_ENCRYPTION_KEY
 */
export function decrypt(encrypted: Buffer, iv: Buffer, tag: Buffer): Buffer {
  return decryptAesGcm(encrypted, iv, tag, getKey());
}

/**
 * Encripta un string y retorna los componentes
 */
export function encryptString(text: string): { encrypted: Buffer; iv: Buffer; tag: Buffer } {
  return encrypt(Buffer.from(text, 'utf-8'));
}

/**
 * Desencripta a string
 */
export function decryptToString(encrypted: Buffer, iv: Buffer, tag: Buffer): string {
  return decrypt(encrypted, iv, tag).toString('utf-8');
}

/**
 * Encripta credenciales FIEL con IV/tag independiente por componente
 */
export function encryptFielCredentials(
  cerData: Buffer,
  keyData: Buffer,
  password: string
): {
  encryptedCer: Buffer;
  encryptedKey: Buffer;
  encryptedPassword: Buffer;
  cerIv: Buffer;
  cerTag: Buffer;
  keyIv: Buffer;
  keyTag: Buffer;
  passwordIv: Buffer;
  passwordTag: Buffer;
} {
  const cer = encrypt(cerData);
  const key = encrypt(keyData);
  const pwd = encrypt(Buffer.from(password, 'utf-8'));

  return {
    encryptedCer: cer.encrypted,
    encryptedKey: key.encrypted,
    encryptedPassword: pwd.encrypted,
    cerIv: cer.iv,
    cerTag: cer.tag,
    keyIv: key.iv,
    keyTag: key.tag,
    passwordIv: pwd.iv,
    passwordTag: pwd.tag,
  };
}

/**
 * Desencripta credenciales FIEL (per-component IV/tag)
 */
export function decryptFielCredentials(
  encryptedCer: Buffer,
  encryptedKey: Buffer,
  encryptedPassword: Buffer,
  cerIv: Buffer,
  cerTag: Buffer,
  keyIv: Buffer,
  keyTag: Buffer,
  passwordIv: Buffer,
  passwordTag: Buffer
): {
  cerData: Buffer;
  keyData: Buffer;
  password: string;
} {
  const cerData = decrypt(encryptedCer, cerIv, cerTag);
  const keyData = decrypt(encryptedKey, keyIv, keyTag);
  const password = decrypt(encryptedPassword, passwordIv, passwordTag).toString('utf-8');

  return { cerData, keyData, password };
}
