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

const nameOfNode = 'dashboardapi';
const nodeClass = require('./src/nodeClass.js');
const { MenuManager } = require('generalFunctions');

module.exports = function (RED) {
  RED.nodes.registerType(nameOfNode, function (config) {
    RED.nodes.createNode(this, config);
    this.nodeClass = new nodeClass(config, RED, this, nameOfNode);
  });

  const menuMgr = new MenuManager();

  RED.httpAdmin.get(`/${nameOfNode}/menu.js`, (req, res) => {
    try {
      const script = menuMgr.createEndpoint(nameOfNode, ['logger']);
      res.type('application/javascript').send(script);
    } catch (err) {
      res.status(500).send(`// Error generating menu: ${err.message}`);
    }
  });

  // Provide config metadata for the editor (local, no dependency on generalFunctions configs).
  RED.httpAdmin.get(`/${nameOfNode}/configData.js`, (req, res) => {
    try {
      const configPath = path.join(__dirname, 'dependencies', 'dashboardapi', 'dashboardapiConfig.json');
      const json = JSON.parse(fs.readFileSync(configPath, 'utf8'));
      const script = `
        window.EVOLV = window.EVOLV || {};
        window.EVOLV.nodes = window.EVOLV.nodes || {};
        window.EVOLV.nodes.${nameOfNode} = window.EVOLV.nodes.${nameOfNode} || {};
        window.EVOLV.nodes.${nameOfNode}.config = ${JSON.stringify(json, null, 2)};
      `;
      res.type('application/javascript').send(script);
    } catch (err) {
      res.status(500).send(`// Error generating configData: ${err.message}`);
    }
  });
};
