// firmware/device/operations/getDevices.methods.ts - COMPLETELY REVISED
import { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow';
import { apiRequest } from '../../../../helpers/apiRequest';
import { logger } from '../../../../helpers/logger';
import { handleApiError } from '../../../../helpers/errorHandler';

/**
 * Retrieves a list of devices with their firmware details
 * GET /firmware/v1/devices
 *
 * @param this The n8n execution context
 * @returns List of devices with firmware details
 */
export async function getDevices(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		// Get device type - THIS IS REQUIRED
		const deviceType = this.getNodeParameter('deviceType', 0) as string;

		// Prepare query parameters
		const queryParams: IDataObject = {
			device_type: deviceType,
		};

		// Add additional filters if provided
		const additionalFields = this.getNodeParameter('additionalFields', 0, {}) as IDataObject;

		if (additionalFields.group) {
			queryParams.group = additionalFields.group;
		}

		// Add pagination parameters
		const returnAll = this.getNodeParameter('returnAll', 0, false) as boolean;
		if (!returnAll) {
			queryParams.limit = this.getNodeParameter('limit', 0, 20) as number;
		}

		// Log request details
		logger.debug('firmware:device:getDevices:request', {
			endpoint: '/firmware/v1/devices',
			queryParams,
		});

		// Make the API request
		const response = await apiRequest.call(
			this,
			'GET',
			'/firmware/v1/devices',
			{}, // No body for GET request
			queryParams,
		);

		// Log response preview
		logger.debug('firmware:device:getDevices:response', {
			responseType: typeof response,
			responseIsNull: response === null,
			responsePreview: response ? JSON.stringify(response).substring(0, 200) : 'null',
		});

		// Return the full response
		return [{ json: response }];
	} catch (error) {
		logger.error('firmware:device:getDevices:error', {
			message: error.message,
			stack: error.stack,
		});
		return handleApiError.call(this, error, 'Failed to retrieve device firmware details');
	}
}
