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

/**
 * Checks whether a specific firmware version is available
 * This uses the compliance endpoint and filters the results
 *
 * @param this The n8n execution context
 * @returns Availability status of the firmware version
 */
export async function checkVersion(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		const deviceType = this.getNodeParameter('deviceType', 0) as string;
		const firmwareVersion = this.getNodeParameter('firmwareVersion', 0) as string;

		if (!deviceType || !firmwareVersion) {
			throw new Error('Device type and firmware version are required');
		}

		const qs: IDataObject = {
			device_type: deviceType,
		};

		// Fetch available versions using the compliance endpoint
		const responseData = await apiRequest.call(
			this,
			'GET',
			'/firmware/v1/compliance',
			{}, // body
			qs,
		);

		// Extract versions from response
		let versions = [];
		if (responseData.data && Array.isArray(responseData.data)) {
			versions = responseData.data;
		} else if (
			responseData.firmware_compliance_versions &&
			Array.isArray(responseData.firmware_compliance_versions)
		) {
			versions = responseData.firmware_compliance_versions;
		} else if (Array.isArray(responseData)) {
			versions = responseData;
		}

		// Check if specified version exists
		const versionFound = versions.some((version: any) => {
			return (
				version.firmware_version === firmwareVersion ||
				version.version === firmwareVersion ||
				version.firmware === firmwareVersion
			);
		});

		// Return result
		return [
			{
				json: {
					available: versionFound,
					supported: versionFound,
					firmware_version: firmwareVersion,
					device_type: deviceType,
				},
			},
		];
	} catch (error) {
		logger.error('firmware:version:checkVersion:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to check firmware version availability');
	}
}
