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

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

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

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

		// No query parameters

		// No body parameters

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

		// Handle pagination
		if (returnAll) {
			// Use the handlePagination helper
			const responseData = await handlePagination.call(
				this,
				endpoint,
				'GET',
				{}, // empty body
				options.qs || {},
				{ path: ['data'] }, // adjust based on your API's response structure
				returnAll,
				this.getNodeParameter('limit', 0, 0) as number,
			);
			return 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:gateway:getPools:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to execute get pools');
	}
}
