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

export class _Schedule implements INodeType {
  description: INodeTypeDescription = {
    displayName: 'Scheduler',
    name: 'schedulerNode',
    group: ['trigger'],
    version: 1,
    description: 'Срабатывает каждый день в заданное время и генерирует JSON + metadata',
    defaults: {
      name: 'Scheduler',
    },
    inputs: [],
    outputs: [NodeConnectionType.Main],
    properties: [
      {
        displayName: 'Часы (0–23)',
        name: 'hour',
        type: 'number',
        default: 9,
        typeOptions: { minValue: 0, maxValue: 23 },
        description: 'Время запуска — часы (по серверу)',
      },
      {
        displayName: 'Минуты (0–59)',
        name: 'minute',
        type: 'number',
        default: 0,
        typeOptions: { minValue: 0, maxValue: 59 },
        description: 'Время запуска — минуты (по серверу)',
      },
      {
        displayName: 'JSON на выходе',
        name: 'jsonOutput',
        type: 'string',
        typeOptions: { rows: 6 },
        default: '{}',
        description: 'Содержимое JSON, которое будет выдано при срабатывании',
      },
    ],
  };

  async trigger(this: ITriggerFunctions): Promise<ITriggerResponse> {
    const hour = this.getNodeParameter('hour', 0) as number;
    const minute = this.getNodeParameter('minute', 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]]);
    };

    // Генерируем cron-строку: "минуты часы * * *"
    const cronExpression = `${minute} ${hour} * * *`;

    const task = cron.schedule(cronExpression, emitFn);

    return {
      closeFunction: async () => {
        task.stop();
      },
    };
  }
}
