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

export class _BaseNodeTrigger implements INodeType {
  description: INodeTypeDescription = {
    displayName: 'BaseNodeTrigger',
    name: 'baseNodeTrigger',
    group: ['trigger'],
    version: 1,
    description: 'Шаблон узла триггера, который эмитит только метадату',
    defaults: {
      name: 'BaseNodeTrigger',
    },
    inputs: [],                  
    outputs: [NodeConnectionType.Main],
    properties: [
      {
        displayName: 'Интервал (мс)',
        name: 'interval',
        type: 'number',
        default: 1000,
        description: 'Интервал между генерациями события',
      },
    ],
  };

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

    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: {},
          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);
      },
    };
  }
}
