'use strict';
const { Router } = require('express');
const { getConfig, setConfig, delConfig, getAllTests } = require('../db');
const { fullScan }      = require('../scanner');
const { startWatching } = require('../watcher');

const router = Router();

const ALLOWED_KEYS = new Set([
  'target_dir', 'results_dir',
  'avg_time_coe', 'avg_time_p2p', 'avg_time_p3p',
]);

router.get('/', (req, res) => {
  const config = {};
  for (const key of ALLOWED_KEYS) {
    config[key] = getConfig(key);
  }
  res.json(config);
});

router.post('/', async (req, res) => {
  const updates = req.body;
  if (!updates || typeof updates !== 'object') {
    return res.status(400).json({ error: 'Request body must be a JSON object' });
  }

  let dirsChanged = false;

  for (const [key, value] of Object.entries(updates)) {
    if (!ALLOWED_KEYS.has(key)) continue;

    if (value === null || value === '') {
      delConfig(key);
    } else {
      setConfig(key, String(value));
    }

    if (key === 'target_dir' || key === 'results_dir') dirsChanged = true;
  }

  if (dirsChanged) {
    const targetDir  = getConfig('target_dir');
    const resultsDir = getConfig('results_dir');
    try {
      await fullScan(targetDir, resultsDir);
    } catch (e) {
      console.error('[config] fullScan error:', e.message);
      return res.status(500).json({ error: `Scan failed: ${e.message}` });
    }
    startWatching(targetDir, resultsDir);
    const tests = getAllTests();
    const completed = tests.filter(t => t.completed).length;
    console.log(`[config] Scan complete — ${tests.length} tests found, ${completed} completed`);
    return res.json({ ok: true, testCount: tests.length, completedCount: completed });
  }

  res.json({ ok: true, testCount: null, completedCount: null });
});

router.post('/rescan', async (req, res) => {
  const targetDir  = getConfig('target_dir');
  const resultsDir = getConfig('results_dir');
  if (!targetDir || !resultsDir) {
    return res.status(400).json({ error: 'Directories not configured' });
  }
  try {
    await fullScan(targetDir, resultsDir);
  } catch (e) {
    console.error('[config] rescan error:', e.message);
    return res.status(500).json({ error: `Scan failed: ${e.message}` });
  }
  startWatching(targetDir, resultsDir);
  const tests = getAllTests();
  const completed = tests.filter(t => t.completed).length;
  console.log(`[config] Rescan complete — ${tests.length} tests, ${completed} completed`);
  res.json({ ok: true, testCount: tests.length, completedCount: completed });
});

module.exports = router;
