import "server-only"

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

import { env } from "@/env.mjs"

const getEncryptionKey = () => {
  const secret = String(env.NEXTAUTH_SECRET ?? "").trim()
  if (!secret) throw new Error("AI encryption secret missing")
  return createHash("sha256").update(secret).digest()
}

export const encryptAiApiKey = (value: string) => {
  const iv = randomBytes(12)
  const key = getEncryptionKey()
  const cipher = createCipheriv("aes-256-gcm", key, iv)
  const encrypted = Buffer.concat([cipher.update(value, "utf8"), cipher.final()])
  const tag = cipher.getAuthTag()
  return Buffer.concat([iv, tag, encrypted]).toString("base64")
}

export const decryptAiApiKey = (value: string) => {
  const raw = Buffer.from(value, "base64")
  if (raw.length < 28) throw new Error("Invalid API key payload")
  const iv = raw.subarray(0, 12)
  const tag = raw.subarray(12, 28)
  const encrypted = raw.subarray(28)
  const key = getEncryptionKey()
  const decipher = createDecipheriv("aes-256-gcm", key, iv)
  decipher.setAuthTag(tag)
  const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()])
  return decrypted.toString("utf8")
}
