const { Api, TelegramClient } = require("telegram");

module.exports = function (RED) {
  function GetFolders(config) {
    RED.nodes.createNode(this, config);
    this.config = RED.nodes.getNode(config.config);
    var node = this;

    this.on("input", async function (msg) {
      /** @type {TelegramClient} */
      const client = msg.payload?.client
        ? msg.payload.client
        : this.config.client;

      try {
        const { filters } = await client.invoke(
          new Api.messages.GetDialogFilters({})
        );

        // Send folder list as output
        node.send({
          payload: { folders: filters },
        });
      } catch (err) {
        // Handle errors
        node.error("Error fetching folders: " + err.message);
      }
    });
  }

  // Register the custom node with Node-RED
  RED.nodes.registerType("get-folders", GetFolders);
};