'use strict';

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

const SERVICES_DIR = path.join(__dirname, '..', 'services');

let routeTable = null;

function loadRoutes() {
  const files = fs.readdirSync(SERVICES_DIR).filter((f) => f.endsWith('.json'));
  const table = files.map((file) => {
    const raw = fs.readFileSync(path.join(SERVICES_DIR, file), 'utf8');
    const config = JSON.parse(raw);
    return {
      name: config.name,
      endpoint: config.endpoint,
      timeout_ms: config.timeout_ms,
      owner: config.owner,
      enabled: config.enabled,
      matcher: buildMatcher(config.name),
    };
  });
  routeTable = table;
  return table;
}

function buildMatcher(serviceName) {
  const prefix = serviceName.toLowerCase();
  return (event) => {
    if (!event.topic) return false;
    return event.topic.toLowerCase().startsWith(prefix);
  };
}

function resolve(event) {
  if (!routeTable) loadRoutes();

  for (const route of routeTable) {
    if (!route.enabled) continue;
    if (route.matcher(event)) return route;
  }

  return null;
}

function reload() {
  routeTable = null;
  return loadRoutes();
}

function listRoutes() {
  if (!routeTable) loadRoutes();
  return routeTable.map((r) => ({ name: r.name, endpoint: r.endpoint }));
}

module.exports = { resolve, reload, listRoutes, loadRoutes };
