// firmware/device/operations/getDevice.methods.ts - FIXED VERSION
import { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow';
import { apiRequest } from '../../../../helpers/apiRequest';
import { logger } from '../../../../helpers/logger';
import { handleApiError } from '../../../../helpers/errorHandler';
import { validateDevice } from '../device.types';

/**
 * Retrieves firmware details for a specific device
 * GET /firmware/v1/devices/{serial}
 *
 * @param this The n8n execution context
 * @returns Firmware details for the specified device
 */
export async function getDevice(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		const serial = this.getNodeParameter('serial', 0) as string;
		const deviceType = this.getNodeParameter('deviceType', 0) as string;

		if (!serial) {
			throw new Error('Device serial number is required');
		}

		// Add device_type as a query parameter
		const qs: IDataObject = {
			device_type: deviceType,
		};

		const responseData = await apiRequest.call(
			this,
			'GET',
			`/firmware/v1/devices/${serial}`,
			{}, // body
			qs, // query params with device_type
		);

		if (!validateDevice(responseData)) {
			throw new Error('Invalid response from API');
		}

		return [{ json: responseData as unknown as IDataObject }];
	} catch (error) {
		logger.error('firmware:device:getDevice:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to retrieve device firmware details');
	}
}
