import {
	INodeType,
	INodeTypeDescription,
	INodeExecutionData,
	IExecuteFunctions,
	NodeConnectionType,
	IDataObject
} from 'n8n-workflow';

export class _Summator implements INodeType {
	description: INodeTypeDescription = {
		displayName: 'Summator',
		name: 'summator',
		icon: 'fa:random',
		group: ['transform'],
		version: 1,
		description: 'Aggregates DATA from multiple inputs into one object',
		defaults: {
			name: 'Summator',
			color: '#772244',
		},
		inputs: [NodeConnectionType.Main],
		outputs: [NodeConnectionType.Main],
		properties: [],
	};

	async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
		const items = this.getInputData();

		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 parsedJson: Record<string, IDataObject> = {};

		for (const item of items) {
			const json = item.json as any; // входные данные лежат в item.json
			if (!json || !json.DATA || !json.METADATA || !json.METADATA.from) continue;

			const key = json.METADATA.from as string;
			parsedJson[key] = json.DATA as IDataObject;
		}

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

		return [[result]];
	}
}
