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

const LOGS_FILE = path.join(__dirname, '..', 'logs', 'connexions.json');
const MAX_LOGS  = 500;

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

function writeLogs(logs) {
  fs.mkdirSync(path.dirname(LOGS_FILE), { recursive: true });
  fs.writeFileSync(LOGS_FILE, JSON.stringify(logs, null, 2), 'utf8');
}

function logLogin({ username, role = null, ip = null, success }) {
  const logs = readLogs();
  logs.unshift({ timestamp: new Date().toISOString(), username, role, ip, success: !!success });
  if (logs.length > MAX_LOGS) logs.length = MAX_LOGS;
  writeLogs(logs);
}

function getLogs(limit = 100) {
  return readLogs().slice(0, limit);
}

module.exports = { logLogin, getLogs };
