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

const DATA_FILE = path.join(__dirname, '..', 'data', 'users.json');

function initUsersFile() {
  if (fs.existsSync(DATA_FILE)) return;
  fs.mkdirSync(path.dirname(DATA_FILE), { recursive: true });
  try {
    const envUsers = JSON.parse(process.env.USERS || '[]');
    fs.writeFileSync(DATA_FILE, JSON.stringify(envUsers, null, 2), 'utf8');
    console.log(`[users] Fichier initialisé depuis .env (${envUsers.length} utilisateurs)`);
  } catch (_) {
    fs.writeFileSync(DATA_FILE, '[]', 'utf8');
  }
}

function getUsers() {
  initUsersFile();
  try {
    return JSON.parse(fs.readFileSync(DATA_FILE, 'utf8'));
  } catch (_) { return []; }
}

function saveUsers(users) {
  fs.mkdirSync(path.dirname(DATA_FILE), { recursive: true });
  fs.writeFileSync(DATA_FILE, JSON.stringify(users, null, 2), 'utf8');
}

module.exports = { getUsers, saveUsers };
