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

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

function getKey() {
  const raw = process.env.CONFIG_KEY;
  if (!raw) {
    throw new Error("CONFIG_KEY fehlt in .env");
  }
  return crypto.createHash("sha256").update(raw).digest(); // 32 bytes
}

function encrypt(obj) {
  const iv = crypto.randomBytes(12);
  const key = getKey();
  const cipher = crypto.createCipheriv("aes-256-gcm", key, iv);

  const data = Buffer.from(JSON.stringify(obj), "utf8");
  const enc = Buffer.concat([cipher.update(data), cipher.final()]);
  const tag = cipher.getAuthTag();

  // [iv(12)] + [tag(16)] + [encData]
  return Buffer.concat([iv, tag, enc]);
}

function decrypt(buf) {
  const iv = buf.subarray(0, 12);
  const tag = buf.subarray(12, 28);
  const enc = buf.subarray(28);

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

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

function loadConfig() {
  if (!fs.existsSync(CONFIG_PATH)) return null;
  const buf = fs.readFileSync(CONFIG_PATH);
  return decrypt(buf);
}

function saveConfig(cfg) {
  const buf = encrypt(cfg);
  fs.writeFileSync(CONFIG_PATH, buf);
}

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