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 Detail
 * GET /monitoring/v1/gateways/{serial}/uplinks
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getDetail(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;
		const timerange = this.getNodeParameter('timerange', 0) as string;

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

		// Set query parameters
		options.qs = options.qs || {};
		if (timerange) {
			options.qs.timerange = timerange;
		}

		// No body parameters

		// Construct API endpoint manually to avoid template literal issues
		const endpoint = '/monitoring/v1/gateways/' + encodeURIComponent(serial) + '/uplinks';
		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:getDetail:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to execute get detail');
	}
}
