import type { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow';

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

/**
 * Get Bssids
 * GET /monitoring/v2/bssids
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getBssids(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 } = {
			offset: 'offset',
			group: 'group',
			swarm_id: 'swarm_id',
			label: 'label',
			site: 'site',
			serial: 'serial',
			macaddr: 'macaddr',
			cluster_id: 'cluster_id',
			calculate_total: 'calculate_total',
			sort: 'sort',
		};

		// 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:getBssids', `Getting BSSIDs with parameters: ${JSON.stringify(qs)}`);

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

		// Use default batch size of 100 for BSSIDs API
		const batchSize = 100;

		// Always use pagination - both for returnAll and limited results
		logger.debug(
			'monitoring:ap:getBssids',
			returnAll ? 'Using pagination to return all BSSIDs' : `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: ['bssids'], // Primary path to look for data
				fallbackPaths: [['data'], ['items']], // Fallback paths
			},
			returnAll,
			limit,
			batchSize,
		);
	} catch (error) {
		logger.error('monitoring:ap:getBssids:error', { message: (error as Error).message });
		return handleApiError.call(this, error, 'Failed to execute get bssids');
	}
}
