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

/**
 * Get Top N Switches
 *
 * GET /monitoring/v1/switches/bandwidth_usage/topn
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getTopNSwitches(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		// Get filter type and corresponding value
		const filterType = this.getNodeParameter('filterType', 0) as string;

		// Get other parameters
		const count = this.getNodeParameter('count', 0) as number;
		const fromTimestamp = this.getNodeParameter('from_timestamp', 0, '') as string;
		const toTimestamp = this.getNodeParameter('to_timestamp', 0, '') as string;

		// Construct query parameters
		const qs: IDataObject = {
			count,
		};

		// Add filter parameter if not "none"
		if (filterType !== 'none') {
			const filterValue = this.getNodeParameter(filterType, 0, '') as string;
			if (filterValue) {
				qs[filterType] = filterValue;
			}
		}

		// Add time range parameters
		if (fromTimestamp) {
			const fromDate = new Date(fromTimestamp);
			qs.from_timestamp = Math.floor(fromDate.getTime() / 1000);
		}

		if (toTimestamp) {
			const toDate = new Date(toTimestamp);
			qs.to_timestamp = Math.floor(toDate.getTime() / 1000);
		}

		logger.debug(
			'monitoring:switch:getTopNSwitches',
			`Getting top ${count} switches with filter ${filterType !== 'none' ? filterType + '=' + qs[filterType] : 'none'}`,
		);

		// Make API request
		const endpoint = '/monitoring/v1/switches/bandwidth_usage/topn';
		const responseData = await apiRequest.call(this, 'GET', endpoint, {}, qs);

		logger.debug('monitoring:switch:getTopNSwitches', 'Successfully retrieved top N switches');

		// Return formatted response
		return [{ json: responseData }];
	} catch (error) {
		logger.error('monitoring:switch:getTopNSwitches:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to get top N switches');
	}
}
