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 Steering History
 * GET /cm-api/ap/{serial}/client-match/steer-history
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getClientMatchSteerHistory(
	this: IExecuteFunctions,
): Promise<INodeExecutionData[]> {
	try {
		// Get parameters
		const serial = this.getNodeParameter('serial', 0) as string;
		const fromTimestamp = this.getNodeParameter('from_timestamp', 0) as number;
		const toTimestamp = this.getNodeParameter('to_timestamp', 0) as number;

		// Construct query parameters
		const queryParams: IDataObject = {};
		if (fromTimestamp) {
			queryParams.from_timestamp = fromTimestamp;
		}
		if (toTimestamp) {
			queryParams.to_timestamp = toTimestamp;
		}

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

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

		// Format and return response
		return [{ json: responseData }];
	} catch (error) {
		logger.error('monitoring:ap:getClientMatchSteerHistory: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 steering history');
	}
}
