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

/**
 * Get Ports
 * GET /monitoring/v1/mobility_controllers/{serial}/ports
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getPorts(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		const returnAll = this.getNodeParameter('returnAll', 0, false) as boolean;

		// Get parameters
		const serial = this.getNodeParameter('serial', 0) as string;

		// Construct request options
		const options: IDataObject = {};

		// Construct API endpoint manually to avoid template literal issues
		const endpoint = '/monitoring/v1/mobility_controllers/' + encodeURIComponent(serial) + '/ports';
		console.log('Constructed endpoint:', endpoint);

		// Handle pagination
		if (returnAll) {
			const responseData: IDataObject[] = await apiRequestAllItems.call(
				this,
				'GET',
				endpoint,
				options,
			);
			return [{ json: responseData }];
		}

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

		// Format and return response
		return [{ json: responseData }];
	} catch (error) {
		logger.error('monitoring:mobilitycontroller:getPorts:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to execute get ports');
	}
}

/**
 * Helper for pagination to fetch all items from a paginated API endpoint
 *
 * @param this The n8n execution context
 * @param method HTTP method to use
 * @param endpoint API endpoint to call
 * @param options Request options
 * @returns Combined array of all items across pages
 */
async function apiRequestAllItems(
	this: IExecuteFunctions,
	method: string,
	endpoint: string,
	options: IDataObject = {},
): Promise<IDataObject[]> {
	const returnData: IDataObject[] = [];
	let responseData;

	const limit = this.getNodeParameter('limit', 0, 0) as number;
	options.qs = options.qs || {};

	let hasMore = true;
	let offset = 0;
	options.qs.limit = limit > 0 ? (limit > 100 ? 100 : limit) : 100;

	do {
		options.qs.offset = offset;
		responseData = await apiRequest.call(this, method, endpoint, options);

		// This needs to be adjusted based on actual API response format
		const items = responseData.items || responseData.data || responseData;

		if (Array.isArray(items)) {
			returnData.push.apply(returnData, items);
		} else {
			returnData.push(items as IDataObject);
		}

		// If limit is set, honor it
		if (limit > 0 && returnData.length >= limit) {
			returnData.splice(limit);
			hasMore = false;
		} else if (items && Array.isArray(items)) {
			// If less items than requested were returned, assume no more items
			if (items.length < options.qs.limit) {
				hasMore = false;
			} else {
				offset += options.qs.limit;
			}
		} else {
			hasMore = false;
		}
	} while (hasMore);

	return returnData;
}
