// config.js - Configuration handling
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import log4js from "log4js";

// Configure paths relative to this file
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const CONFIG_PATH = path.resolve(__dirname, "../config.json");

const logger = log4js.getLogger("Config");
logger.level = "info";

// Determine environment
const NODE_ENV = process.env.NODE_ENV || "development";

// Load config file
export function loadConfig() {
  try {
    if (!fs.existsSync(CONFIG_PATH)) {
      throw new Error(`Configuration file not found at ${CONFIG_PATH}`);
    }

    const configData = fs.readFileSync(CONFIG_PATH, "utf8");
    const config = JSON.parse(configData);

    if (!config[NODE_ENV]) {
      throw new Error(
        `Configuration for environment '${NODE_ENV}' not found in config.json`
      );
    }

    return config[NODE_ENV];
  } catch (err) {
    console.error("Error loading config:", err);
    throw err;
  }
}

// Save config file
export function saveConfig(newConfig) {
  try {
    logger.info("Saving...");
    let config = {};
    if (fs.existsSync(CONFIG_PATH)) {
      const configData = fs.readFileSync(CONFIG_PATH, "utf8");
      config = JSON.parse(configData);
    }

    // Update current environment
    config[NODE_ENV] = newConfig;

    // Write back to file with 2-space indentation
    fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2), "utf8");
    logger.info(`Configuration for '${NODE_ENV}' saved successfully.`);
  } catch (err) {
    logger.error("Error saving config:", err);
    throw err;
  }
}

// Get current environment
export function getEnvironment() {
  return NODE_ENV;
}
