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

/**
 * Get Ports Bandwidth Usage for CX Switch
 *
 * GET /monitoring/v1/cx_switches/{serial}/ports/bandwidth_usage
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getCxSwitchPortsBandwidthUsage(
	this: IExecuteFunctions,
): Promise<INodeExecutionData[]> {
	try {
		// Get parameters
		const serial = this.getNodeParameter('serial', 0) as string;
		const fromTimestamp = this.getNodeParameter('from_timestamp', 0, '') as string;
		const toTimestamp = this.getNodeParameter('to_timestamp', 0, '') as string;
		const additionalFields = this.getNodeParameter('additionalFields', 0, {}) as IDataObject;

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

		// 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);
		}

		// Add port parameter if provided
		if (additionalFields.port !== undefined && additionalFields.port !== '') {
			qs.port = additionalFields.port;
		}

		// Add show_uplink parameter if provided
		if (additionalFields.show_uplink !== undefined) {
			qs.show_uplink = additionalFields.show_uplink;
		}

		logger.debug(
			'monitoring:switch:getCxSwitchPortsBandwidthUsage',
			`Getting ports bandwidth usage for CX switch with serial: ${serial}`,
		);

		// Make API request
		const endpoint = `/monitoring/v1/cx_switches/${encodeURIComponent(serial)}/ports/bandwidth_usage`;
		const responseData = await apiRequest.call(this, 'GET', endpoint, {}, qs);

		logger.debug(
			'monitoring:switch:getCxSwitchPortsBandwidthUsage',
			'Successfully retrieved CX switch ports bandwidth usage',
		);

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