'use strict';

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

const DATA_DIR = process.env.RELAY_DATA_DIR || path.join(__dirname, '..', 'data');
const LOG_FILE = path.join(DATA_DIR, 'events.log');

const events = [];

function ensureDataDir() {
  if (!fs.existsSync(DATA_DIR)) {
    fs.mkdirSync(DATA_DIR, { recursive: true });
  }
}

function append(event) {
  events.push(event);
  ensureDataDir();
  fs.appendFile(LOG_FILE, JSON.stringify(event) + '\n', (err) => {
    if (err) console.error('failed to persist event', err.message);
  });
}

function all() {
  return events;
}

function findById(id) {
  return events.find((e) => e.id === id);
}

function replayFromDisk() {
  ensureDataDir();
  if (!fs.existsSync(LOG_FILE)) return [];

  const raw = fs.readFileSync(LOG_FILE, 'utf8');
  const lines = raw.split('\n').filter(Boolean);
  const restored = lines.map((line) => JSON.parse(line));

  events.length = 0;
  for (const event of restored) {
    events.push(event);
  }

  return events;
}

function clear() {
  events.length = 0;
}

module.exports = { append, all, findById, replayFromDisk, clear };
