// api/inventory/devices/addDevice.methods.ts
import { IExecuteFunctions, INodeExecutionData } from 'n8n-workflow';
import { apiRequest } from '../../../helpers/apiRequest';
import { formatResponse } from '../../../helpers/responseFormatter';
import { logger } from '../../../helpers/logger';

export async function addDevice(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	logger.info('inventory:devices:addDevice', 'Starting addDevice operation');
	try {
		const mac = this.getNodeParameter('mac', 0) as string;
		const serial = this.getNodeParameter('serial', 0) as string;
		const partNumber = this.getNodeParameter('partNumber', 0) as string;

		const deviceObject: { [key: string]: any } = {
			mac,
			serial,
		};

		if (partNumber) {
			deviceObject.partNumber = partNumber;
		}

		// The API expects an array of devices, even for single device
		const requestBody = [deviceObject];

		logger.debug(
			'inventory:devices:addDevice',
			`Adding device with MAC: ${mac}, Serial: ${serial}`,
		);

		// Make API request
		const response = await apiRequest.call(
			this,
			'POST',
			'/platform/device_inventory/v1/devices',
			requestBody,
			{},
		);

		logger.info('inventory:devices:addDevice', 'Device added successfully');
		return formatResponse(response);
	} catch (error) {
		logger.error('inventory:devices:addDevice:error', error.message);
		throw error;
	}
}
