const DatabaseClient = require('./db');
const config = require('../../config/default');

class InstrumentConfigStore {
  constructor() {
    this.db = new DatabaseClient(config.db);
  }

  async list() {
    return this.db.all(`SELECT instrument_id, connector, enabled, config FROM instrument_config`);
  }

  async get(instrumentId) {
    return this.db.get(
      `SELECT instrument_id, connector, enabled, config FROM instrument_config WHERE instrument_id = ?`,
      [instrumentId]
    );
  }

  async upsert({ instrument_id, connector, enabled = 1, config: cfg = {} }) {
    const payload = JSON.stringify(cfg);
    await this.db.run(
      `INSERT INTO instrument_config (instrument_id, connector, enabled, config) VALUES (?, ?, ?, ?)
       ON CONFLICT(instrument_id) DO UPDATE SET connector = excluded.connector, enabled = excluded.enabled, config = excluded.config`,
      [instrument_id, connector, Number(enabled), payload]
    );
    return this.get(instrument_id);
  }
}

module.exports = new InstrumentConfigStore();
