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

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

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

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

		// Add filter parameter
		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:getSwitchBandwidthUsage',
			`Getting bandwidth usage with filter ${filterType}=${filterValue}, time range: ${fromTimestamp} - ${toTimestamp}`,
		);

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

		logger.debug(
			'monitoring:switch:getSwitchBandwidthUsage',
			'Successfully retrieved switch bandwidth usage',
		);

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