// api/monitoring/ap/operations/getAps.methods.ts
import type { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow';

import { handleApiError } from '../../../../helpers/errorHandler';
import { logger } from '../../../../helpers/logger';
import { handlePagination } from '../../../../helpers/pagination';

/**
 * Get Aps
 * GET /monitoring/v2/aps
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getAps(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		const returnAll = this.getNodeParameter('returnAll', 0, false);
		const limit = returnAll ? 0 : this.getNodeParameter('limit', 0, 50);

		// Get additional fields
		const additionalFields = this.getNodeParameter('additionalFields', 0, {});

		// Construct query parameters directly (not inside options object)
		const qs: IDataObject = {};

		// Map all additional fields to query parameters
		const paramMappings: { [key: string]: string } = {
			group: 'group',
			swarm_id: 'swarm_id',
			label: 'label',
			site: 'site',
			status: 'status',
			serial: 'serial',
			macaddr: 'macaddr',
			model: 'model',
			cluster_id: 'cluster_id',
			fields: 'fields',
			calculate_total: 'calculate_total',
			calculate_client_count: 'calculate_client_count',
			calculate_ssid_count: 'calculate_ssid_count',
			show_resource_details: 'show_resource_details',
			sort: 'sort',
			offset: 'offset',
			api_limit: 'limit',
		};

		// Process all additional fields and map to query parameters
		for (const [key, apiParam] of Object.entries(paramMappings)) {
			if (additionalFields[key] !== undefined && additionalFields[key] !== '') {
				qs[apiParam] = additionalFields[key];
				logger.debug(`parameter:${key}`, `Setting ${apiParam} to ${String(additionalFields[key])}`);
			}
		}

		logger.debug('monitoring:ap:getAps', `Getting APs with parameters: ${JSON.stringify(qs)}`);

		// Define the endpoint
		const endpoint = '/monitoring/v2/aps';

		// Determine batch size from API limit parameter or use default
		const batchSize = (additionalFields.api_limit as number) || 100;

		// Always use pagination - both for returnAll and limited results
		logger.debug(
			'monitoring:ap:getAps',
			returnAll ? 'Using pagination to return all APs' : `Using pagination with limit ${limit}`,
		);

		// Use the pagination helper for both returnAll and limited results
		return await handlePagination.call(
			this,
			endpoint,
			'GET',
			{}, // Empty body
			qs, // Query parameters
			{
				path: ['aps'], // Primary path to look for data
				fallbackPaths: [['data'], ['items']], // Fallback paths
			},
			returnAll,
			limit,
			batchSize, // Use the API limit parameter as batch size
		);
	} catch (error) {
		logger.error('monitoring:ap:getAps:error', { message: (error as Error).message });
		return handleApiError.call(this, error, 'Failed to execute get aps');
	}
}
