'use strict';
/**
 * In-memory test store + JSON-file config persistence.
 * No native modules required.
 */
const fs   = require('fs');
const path = require('path');

const CONFIG_PATH = path.join(__dirname, 'config.json');

// ── Config ───────────────────────────────────────────────────────────────────
let _config = {};
try {
  if (fs.existsSync(CONFIG_PATH)) {
    _config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
  }
} catch { _config = {}; }

function _saveConfig() {
  fs.writeFileSync(CONFIG_PATH, JSON.stringify(_config, null, 2));
}

function getConfig(key)        { return _config[key] ?? null; }
function setConfig(key, value) { _config[key] = value; _saveConfig(); }
function delConfig(key)        { delete _config[key]; _saveConfig(); }

// ── Tests (keyed by full derived ID) ─────────────────────────────────────────
/** @type {Map<string, object>} */
const _tests = new Map();

function upsertTest(test) {
  const existing = _tests.get(test.id);
  _tests.set(test.id, {
    ...test,
    // Preserve completion state when re-inserting from a target scan
    completed:        existing ? existing.completed        : 0,
    completed_at:     existing ? existing.completed_at     : null,
    duration_seconds: existing ? existing.duration_seconds : null,
  });
}

function markCompleted(file_id, device, completed_at, duration_seconds) {
  for (const [id, test] of _tests) {
    if (test.file_id === file_id && (!device || test.device === device)) {
      _tests.set(id, { ...test, completed: 1, completed_at, duration_seconds });
    }
  }
}

function resetByFileIdAndDevice(file_id, device) {
  for (const [id, test] of _tests) {
    if (test.file_id === file_id && (!device || test.device === device)) {
      _tests.set(id, { ...test, completed: 0, completed_at: null, duration_seconds: null });
    }
  }
}

function clearTests()  { _tests.clear(); }
function getAllTests()  { return Array.from(_tests.values()); }

module.exports = {
  getConfig, setConfig, delConfig,
  upsertTest, markCompleted, resetByFileIdAndDevice, clearTests, getAllTests,
};
