const fs = require('fs');
const path = require('path');

const loadEnv = (mode) => {
  const basePath = process.cwd();
  const envPath = path.resolve(basePath, `.env.${mode}`);
  const defaultEnvPath = path.resolve(basePath, '.env');

  try {
    let envConfig = {};

    if (fs.existsSync(envPath)) {
      const envFile = fs.readFileSync(envPath, 'utf8');
      envFile.split('\n').forEach((line) => {
        const [key, value] = line.split('=');
        if (key && value) {
          envConfig[key.trim()] = value.trim();
        }
      });
    } else if (fs.existsSync(defaultEnvPath)) {
      const envFile = fs.readFileSync(defaultEnvPath, 'utf8');
      envFile.split('\n').forEach((line) => {
        const [key, value] = line.split('=');
        if (key && value) {
          envConfig[key.trim()] = value.trim();
        }
      });
    }

    return envConfig;
  } catch (error) {
    console.error('Error loading .env file:', error);
    return {};
  }
};

module.exports = loadEnv;