import {
  INodeType,
  INodeTypeDescription,
  ITriggerFunctions,
  ITriggerResponse,
  INodeExecutionData,
  NodeConnectionType,
} from 'n8n-workflow';

export class _Generator implements INodeType {
  description: INodeTypeDescription = {
    displayName: 'Generator',
    name: 'generatorNode',
    group: ['trigger'],
    version: 1,
    description: 'Срабатывает по интервалу и генерирует JSON + metadata',
    defaults: {
      name: 'Generator',
    },
    inputs: [],                  
    outputs: [NodeConnectionType.Main],
    properties: [
      {
        displayName: 'Повторять раз в (мс)',
        name: 'interval',
        type: 'number',
        default: 1000,
        description: 'Интервал между генерацией данных',
      },
      {
        displayName: 'JSON на выходе',
        name: 'jsonOutput',
        type: 'string',
        typeOptions: { rows: 6 },
        default: '{}',
        description: 'Содержимое JSON, которое будет выдано',
      },
     
    ],
  };

  async trigger(this: ITriggerFunctions): Promise<ITriggerResponse> {
    const interval = this.getNodeParameter('interval', 0) as number;
    const jsonOutputStr = this.getNodeParameter('jsonOutput', 0) as string;

    let parsedJson: any;
    try {
      parsedJson = JSON.parse(jsonOutputStr);
    } catch (error) {
      throw new Error('Ошибка при разборе JSON: ' + error);
    }

  
    const workflowName = this.getWorkflow?.()?.name || '';
    const nodeInfo = this.getNode();
    const fromNodeFull = nodeInfo.type; 
    const fromNode = fromNodeFull.includes('.') ? fromNodeFull.split('.').pop()! : fromNodeFull;

    const idField = nodeInfo.name as string;

    const emitFn = () => {
      const data: INodeExecutionData = {
        json: {
          DATA:{
              ...parsedJson,
          },
          METADATA: {
            chain: workflowName,
            from: fromNode,
            id: idField,
            time: Date.now(),
          },
        },
        pairedItem: 0,
      };

      this.emit([[data]]);
    };

    const intervalId = setInterval(emitFn, interval);

    return {
      closeFunction: async () => {
        clearInterval(intervalId);
      },
    };
  }
}
