import { createCipheriv, createDecipheriv, randomBytes, scryptSync } from "crypto";

import { env } from "@/config/env";

const ALGORITHM = "aes-256-gcm";
const IV_LENGTH = 12;

function getKey(): Buffer {
  const secret = env.encryptionKey;
  if (!secret) {
    throw new Error("ENCRYPTION_KEY não está definida nas variáveis de ambiente");
  }
  return scryptSync(secret, "newsletter-platform-salt", 32);
}

/** Criptografa um texto em claro (ex: smtpPass) antes de persistir no banco. */
export function encrypt(plainText: string): string {
  const key = getKey();
  const iv = randomBytes(IV_LENGTH);
  const cipher = createCipheriv(ALGORITHM, key, iv);

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

  return [iv.toString("hex"), authTag.toString("hex"), encrypted.toString("hex")].join(":");
}

/** Descriptografa um valor gerado por encrypt() — usado ao montar o transporte SMTP. */
export function decrypt(cipherText: string): string {
  const [ivHex, authTagHex, dataHex] = cipherText.split(":");
  if (!ivHex || !authTagHex || !dataHex) {
    throw new Error("Formato de texto criptografado inválido");
  }

  const key = getKey();
  const decipher = createDecipheriv(ALGORITHM, key, Buffer.from(ivHex, "hex"));
  decipher.setAuthTag(Buffer.from(authTagHex, "hex"));

  const decrypted = Buffer.concat([
    decipher.update(Buffer.from(dataHex, "hex")),
    decipher.final(),
  ]);

  return decrypted.toString("utf8");
}
