const store = require('../storage/instrumentConfigStore');
const logger = require('../utils/logger');

let cache = new Map();
let refreshInterval;

async function reload() {
  const rows = await store.list();
  const next = new Map();
  rows.forEach((row) => {
    try {
      const config = row.config ? JSON.parse(row.config) : {};
      next.set(row.instrument_id, { instrument_id: row.instrument_id, connector: row.connector, enabled: Boolean(row.enabled), config });
    } catch (err) {
      logger.warn({ instrument: row.instrument_id, err: err.message }, 'failed parsing instrument config, skipping');
    }
  });
  cache = next;
}

async function init({ refreshMs = 30_000 } = {}) {
  await reload();
  if (refreshInterval) clearInterval(refreshInterval);
  refreshInterval = setInterval(() => {
    reload().catch((err) => logger.error({ err: err.message }, 'instrument config reload failed'));
  }, refreshMs);
}

function list() {
  return Array.from(cache.values());
}

function get(instrumentId) {
  return cache.get(instrumentId) || null;
}

function byConnector(connector) {
  return list().filter((entry) => entry.connector === connector && entry.enabled);
}

async function upsert(payload) {
  const stored = await store.upsert(payload);
  await reload();
  return get(stored.instrument_id);
}

module.exports = {
  init,
  list,
  get,
  byConnector,
  upsert
};
