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 VLAN Info of the Switch Stack
 *
 * GET /monitoring/v1/switch_stacks/{stack_id}/vlan
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getSwitchStackVlanInfo(
	this: IExecuteFunctions,
): Promise<INodeExecutionData[]> {
	try {
		// Get parameters
		const stackId = this.getNodeParameter('stack_id', 0) as string;
		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 } = {
			name: 'name',
			id: 'id',
			tagged_port: 'tagged_port',
			untagged_port: 'untagged_port',
			is_jumbo_enabled: 'is_jumbo_enabled',
			is_voice_enabled: 'is_voice_enabled',
			is_igmp_enabled: 'is_igmp_enabled',
			type: 'type',
			primary_vlan_id: 'primary_vlan_id',
			status: 'status',
			sort: 'sort',
			calculate_total: 'calculate_total',
		};

		// 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:getSwitchStackVlanInfo',
			`Getting VLAN info for switch stack with ID: ${stackId}`,
		);

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

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

		logger.debug(
			'monitoring:switch:getSwitchStackVlanInfo',
			'Successfully retrieved switch stack VLAN info',
		);

		// Return formatted response
		return [{ json: responseData }];
	} catch (error) {
		logger.error('monitoring:switch:getSwitchStackVlanInfo:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to get switch stack VLAN info');
	}
}
