import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";

/** Derive a stable 32-byte key from env. Prefer INTEGRATIONS_ENCRYPTION_KEY. */
function encryptionKey(): Buffer {
  const raw = process.env.INTEGRATIONS_ENCRYPTION_KEY || process.env.JWT_ACCESS_SECRET || "dev-insecure-integrations-key";
  return createHash("sha256").update(raw).digest();
}

/** AES-256-GCM; format `v1:iv:tag:ciphertext` (base64url). */
export function encryptSecret(plain: string): string {
  const iv = randomBytes(12);
  const cipher = createCipheriv("aes-256-gcm", encryptionKey(), iv);
  const enc = Buffer.concat([cipher.update(plain, "utf8"), cipher.final()]);
  const tag = cipher.getAuthTag();
  return `v1:${iv.toString("base64url")}:${tag.toString("base64url")}:${enc.toString("base64url")}`;
}

export function decryptSecret(payload: string): string {
  const [version, ivB64, tagB64, dataB64] = payload.split(":");
  if (version !== "v1" || !ivB64 || !tagB64 || !dataB64) {
    throw new Error("invalid encrypted secret");
  }
  const decipher = createDecipheriv("aes-256-gcm", encryptionKey(), Buffer.from(ivB64, "base64url"));
  decipher.setAuthTag(Buffer.from(tagB64, "base64url"));
  return Buffer.concat([decipher.update(Buffer.from(dataB64, "base64url")), decipher.final()]).toString("utf8");
}
