// firmware/upgrade/operations/cancelUpgrade.methods.ts - FIXED
import { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow';
import { apiRequest } from '../../../../helpers/apiRequest';
import { logger } from '../../../../helpers/logger';
import { handleApiError } from '../../../../helpers/errorHandler';

/**
 * Cancels a scheduled firmware upgrade
 * POST /firmware/v1/cancel_upgrade
 *
 * @param this The n8n execution context
 * @returns Result of the cancel operation
 */
export async function cancelUpgrade(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		const deviceType = this.getNodeParameter('deviceType', 0) as string;
		const targetType = this.getNodeParameter('targetType', 0) as string;
		const targetValue = this.getNodeParameter('targetValue', 0) as string;

		// Create request body
		const body: IDataObject = {
			device_type: deviceType,
		};

		// Add target parameter based on target type
		if (targetType && targetValue) {
			body[targetType] = targetValue;
		}

		// Log the request for debugging
		logger.debug('firmware:upgrade:cancelUpgrade:request', {
			url: '/firmware/v1/cancel_upgrade',
			body: JSON.stringify(body),
		});

		// Make the API request
		const responseData = await apiRequest.call(
			this,
			'POST',
			'/firmware/v1/cancel_upgrade',
			body,
			{}, // query params
		);

		// Log the response for debugging
		logger.debug('firmware:upgrade:cancelUpgrade:response', {
			responseData: JSON.stringify(responseData).substring(0, 500), // Truncate for logging
		});

		return [{ json: responseData }];
	} catch (error) {
		logger.error('firmware:upgrade:cancelUpgrade:error', {
			message: error.message,
			stack: error.stack,
		});
		return handleApiError.call(this, error, 'Failed to cancel firmware upgrade');
	}
}
