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

/**
 * Get Client Match Info
 * GET /cm-api/ap/{serial}/client-match/client-info
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getClientMatchInfo(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		// Get parameters
		const serial = this.getNodeParameter('serial', 0) as string;

		// Construct API endpoint
		const endpoint = '/cm-api/ap/' + encodeURIComponent(serial) + '/client-match/client-info';
		logger.debug('monitoring:ap:getClientMatchInfo', `Requesting: ${endpoint}`);

		// Make API request
		const responseData = await apiRequest.call(this, 'GET', endpoint, {});

		// Format and return response
		return [{ json: responseData }];
	} catch (error) {
		logger.error('monitoring:ap:getClientMatchInfo:error', { message: error.message });

		// Handle 404 specifically for ClientMatch APIs which may not be available on all clusters
		if (error.httpCode === 404 || error.message?.includes('404')) {
			return handleApiError.call(
				this,
				error,
				'ClientMatch API not available on this cluster or AP does not support ClientMatch. This is an undocumented API that may not be enabled for all devices.',
			);
		}

		return handleApiError.call(this, error, 'Failed to get client match info');
	}
}
