import { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow';
import { apiRequest } from '../../../../helpers/apiRequest';
import { logger } from '../../../../helpers/logger';
import { handleApiError } from '../../../../helpers/errorHandler';

/**
 * Patch Label
 * PATCH /central/v1/labels/{label_id}
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function patchLabel(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		// Get parameters
		const label_id = this.getNodeParameter('label_id', 0) as number;

		// Construct request options
		const options: IDataObject = {};

		// Construct API endpoint manually to avoid template literal issues
		const endpoint = '/central/v1/labels/' + encodeURIComponent(label_id);
		console.log('Constructed endpoint:', endpoint);

		// Make API request
		const responseData = await apiRequest.call(this, 'PATCH', endpoint, options);

		// Format and return response
		return [{ json: responseData }];
	} catch (error) {
		logger.error('monitoring:label:patchLabel:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to execute patch label');
	}
}
