// firmware/upgrade/operations/setComplianceVersion.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';

/**
 * Sets firmware compliance version for a device type
 * POST /firmware/v1/compliance
 *
 * @param this The n8n execution context
 * @returns Result of setting compliance version
 */
export async function setComplianceVersion(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		const deviceType = this.getNodeParameter('deviceType', 0) as string;
		const firmwareVersion = this.getNodeParameter('firmwareVersion', 0) as string;
		const options = this.getNodeParameter('options', 0, {}) as IDataObject;

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

		// Add optional parameters
		if (options.group) {
			body.group = options.group;
		}

		if (options.reboot !== undefined) {
			body.reboot = options.reboot;
		}

		if (options.allowUnsupportedVersion !== undefined) {
			body.allow_unsupported_version = options.allowUnsupportedVersion;
		}

		if (options.complianceScheduledAt) {
			body.compliance_scheduled_at = options.complianceScheduledAt;
		}

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

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

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

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