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';

/**
 * List Switch Stacks
 *
 * GET /monitoring/v1/switch_stacks
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function listSwitchStacks(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		const returnAll = this.getNodeParameter('returnAll', 0, false) as boolean;
		const limit = returnAll ? 0 : (this.getNodeParameter('limit', 0, 50) as number);
		const additionalFields = this.getNodeParameter('additionalFields', 0, {}) as IDataObject;

		// Construct query parameters
		const qs: IDataObject = {};

		// Map all additional fields to query parameters
		const paramMappings: { [key: string]: string } = {
			hostname: 'hostname',
			group: 'group',
		};

		// 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(
			'monitoring:switch:listSwitchStacks',
			`Listing switch stacks with parameters: ${JSON.stringify(qs)}`,
		);

		// Handle pagination
		if (!returnAll && limit > 0) {
			qs.limit = limit;
			return await handlePagination.call(
				this,
				'/monitoring/v1/switch_stacks',
				'GET',
				{},
				qs,
				{ path: ['stacks'] },
				returnAll,
				limit,
			);
		}

		// Make API request
		const endpoint = '/monitoring/v1/switch_stacks';
		const responseData = await apiRequest.call(this, 'GET', endpoint, {}, qs);

		logger.debug('monitoring:switch:listSwitchStacks', 'Successfully retrieved switch stacks list');

		// Return formatted response
		return [{ json: responseData }];
	} catch (error) {
		logger.error('monitoring:switch:listSwitchStacks:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to list switch stacks');
	}
}
