const fs = require("fs");
const crypto = require("crypto");
const path = require("path");

const CONFIG_FILE = path.join(__dirname, "config.enc");

function getKey() {
  const key = process.env.CONFIG_KEY;
  if (!key) throw new Error("CONFIG_KEY fehlt in .env");

  // stabil auf 32 bytes
  return crypto.createHash("sha256").update(key).digest();
}

function encryptConfig(obj) {
  const key = getKey();
  const iv = crypto.randomBytes(12);

  const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);
  const json = JSON.stringify(obj);

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

  return Buffer.concat([iv, tag, encrypted]).toString("base64");
}

function decryptConfig(str) {
  const raw = Buffer.from(str, "base64");

  const iv = raw.subarray(0, 12);
  const tag = raw.subarray(12, 28);
  const encrypted = raw.subarray(28);

  const key = getKey();

  const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
  decipher.setAuthTag(tag);

  const decrypted = Buffer.concat([
    decipher.update(encrypted),
    decipher.final(),
  ]);
  return JSON.parse(decrypted.toString("utf8"));
}

function configExists() {
  return fs.existsSync(CONFIG_FILE);
}

function loadConfig() {
  if (!configExists()) return null;
  const enc = fs.readFileSync(CONFIG_FILE, "utf8").trim();
  if (!enc) return null;
  return decryptConfig(enc);
}

function saveConfig(obj) {
  const enc = encryptConfig(obj);
  fs.writeFileSync(CONFIG_FILE, enc, "utf8");
  return true;
}

module.exports = {
  configExists,
  loadConfig,
  saveConfig,
};
