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

const cache = {};

function loadLocale(lang) {
  if (cache[lang]) return cache[lang];
  try {
    const filePath = path.join(__dirname, lang + '.json');
    if (fs.existsSync(filePath)) {
      cache[lang] = JSON.parse(fs.readFileSync(filePath, 'utf8'));
      return cache[lang];
    }
  } catch (e) {}
  return loadLocale('nl');
}

function t(lang, key, ...args) {
  const dict = loadLocale(lang || 'nl');
  let val = dict[key] || key;
  if (args.length > 0) {
    args.forEach((a, i) => { val = val.replace(`{${i}}`, a); });
  }
  return val;
}

function localeMiddleware(req, res, next) {
  const lang = (req.session && req.session.lang) || 'nl';
  res.locals.__ = (key, ...args) => t(lang, key, ...args);
  res.locals.lang = lang;
  next();
}

module.exports = { t, loadLocale, localeMiddleware };
