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

/**
 * Retrieves firmware upgrade status for a device
 * GET /firmware/v1/status
 *
 * @param this The n8n execution context
 * @returns Status of firmware upgrade for the device
 */
export async function getStatus(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		// Get the type of identifier (swarm_id or serial)
		const identifierType = this.getNodeParameter('identifierType', 0) as string;

		// Get identifier value
		const identifier = this.getNodeParameter('identifier', 0) as string;

		if (!identifier) {
			throw new Error('Please provide either a swarm ID or a device serial number');
		}

		// Set up query parameters
		const queryParameters: IDataObject = {};
		queryParameters[identifierType] = identifier;

		// Log the request for debugging
		logger.debug('firmware:status:getStatus:request', {
			url: '/firmware/v1/status',
			queryParameters,
		});

		// Make the API request
		const responseData = await apiRequest.call(
			this,
			'GET',
			'/firmware/v1/status',
			{}, // body
			queryParameters,
		);

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

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