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

// Load environment variables from .env file
dotenv.config();

// 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');

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

// Load config file
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`);
    }

    const envConfig = config[NODE_ENV];

    // Ensure auth config exists
    if (!envConfig.auth) {
      envConfig.auth = {};
    }
    if (!envConfig.auth.keycloak) {
      envConfig.auth.keycloak = {};
    }

    // Override secrets with environment variables if available
    if (process.env.KEYCLOAK_CLIENT_SECRET) {
      envConfig.auth.keycloak.clientSecret = process.env.KEYCLOAK_CLIENT_SECRET;
    }

    // Session secret must be set - use env var or throw error
    if (process.env.SESSION_SECRET) {
      envConfig.auth.sessionSecret = process.env.SESSION_SECRET;
    } else if (!envConfig.auth.sessionSecret) {
      throw new Error(
        'SESSION_SECRET environment variable is required. Please set SESSION_SECRET in your environment.'
      );
    }

    return envConfig;
  } catch (err) {
    console.error('Error loading config:', err);
    throw err;
  }
}

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

// Export singleton config instance
const config = loadConfig();
export default config;
