// api/rapids/rogues/operations/getSuspectApList.methods.ts
import { IExecuteFunctions, INodeExecutionData } from 'n8n-workflow';
import { apiRequest } from '../../../../helpers/apiRequest';
import { handleApiError } from '../../../../helpers/errorHandler';
import { logger } from '../../../../helpers/logger';
import { formatResponse } from '../../../../helpers/responseFormatter';
import { handlePagination } from '../../../../helpers/pagination';

/**
 * Get suspect APs over a time period
 *
 * @param this The n8n execution context
 * @returns List of suspect APs
 */
export async function getSuspectApList(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		const returnAll = this.getNodeParameter('returnAll', 0, true) as boolean;
		const limit = this.getNodeParameter('limit', 0, 100) as number;
		const additionalFields = this.getNodeParameter('additionalFields', 0, {}) as Record<
			string,
			any
		>;

		logger.debug('rapids:rogues:getSuspectApList', 'Retrieving suspect AP list');

		// Build query parameters - using a simple object first
		const queryParams: Record<string, any> = {};

		// Add time range parameters
		try {
			const timeRange = this.getNodeParameter('timeRange', 0, {}) as Record<string, any>;
			if (timeRange.from_timestamp) {
				queryParams.from_timestamp = Math.floor(
					new Date(timeRange.from_timestamp).getTime() / 1000,
				);
			}
			if (timeRange.to_timestamp) {
				queryParams.to_timestamp = Math.floor(new Date(timeRange.to_timestamp).getTime() / 1000);
			}
		} catch (e) {
			// Time range not specified
		}

		// Add pagination limit
		if (!returnAll) {
			queryParams.limit = limit;
		}

		// Create a URLSearchParams object for proper query parameter formatting
		const urlParams = new URLSearchParams();

		// Add non-array parameters
		Object.entries(queryParams).forEach(([key, value]) => {
			if (value !== undefined && value !== null && value !== '') {
				urlParams.append(key, value.toString());
			}
		});

		// Handle array parameters specially
		if (additionalFields.site) {
			const siteValues = additionalFields.site
				.split(',')
				.map((s: string) => s.trim())
				.filter((s: string) => s !== '');

			siteValues.forEach((site: string) => {
				urlParams.append('site', site);
			});
		}

		if (additionalFields.group) {
			const groupValues = additionalFields.group
				.split(',')
				.map((g: string) => g.trim())
				.filter((g: string) => g !== '');

			groupValues.forEach((group: string) => {
				urlParams.append('group', group);
			});
		}

		if (additionalFields.label) {
			const labelValues = additionalFields.label
				.split(',')
				.map((l: string) => l.trim())
				.filter((l: string) => l !== '');

			labelValues.forEach((label: string) => {
				urlParams.append('label', label);
			});
		}

		if (additionalFields.swarm_id && additionalFields.swarm_id.trim() !== '') {
			urlParams.append('swarm_id', additionalFields.swarm_id.trim());
		}

		// Convert URLSearchParams to plain object for apiRequest
		const finalQueryParams: Record<string, any> = {};
		urlParams.forEach((value, key) => {
			// If we have multiple values for the same key, create an array
			if (finalQueryParams[key] === undefined) {
				finalQueryParams[key] = value;
			} else if (Array.isArray(finalQueryParams[key])) {
				finalQueryParams[key].push(value);
			} else {
				finalQueryParams[key] = [finalQueryParams[key], value];
			}
		});

		logger.debug('rapids:rogues:getSuspectApList:params', JSON.stringify(finalQueryParams));

		const endpoint = '/rapids/v1/suspect_aps';

		// Use pagination or direct request
		if (returnAll) {
			return await handlePagination.call(
				this,
				endpoint,
				'GET',
				{},
				finalQueryParams,
				{
					path: ['suspect_aps'],
					fallbackPaths: [['data', 'suspect_aps']],
				},
				true,
				undefined,
				1000,
			);
		} else {
			// Log request parameters
			logger.debug('rapids:rogues:getSuspectApList:request', {
				method: 'GET',
				endpoint,
				queryParams: finalQueryParams,
			});

			const response = await apiRequest.call(this, 'GET', endpoint, {}, finalQueryParams);

			// Log response details
			if (response) {
				logger.debug('rapids:rogues:getSuspectApList:response', {
					count: response.count,
					total: response.total,
					items: response.suspect_aps ? response.suspect_aps.length : 0,
				});
			}

			return formatResponse(response);
		}
	} catch (error) {
		logger.error('rapids:rogues:getSuspectApList:error', error.message);
		return handleApiError.call(this, error, 'Failed to retrieve suspect AP list');
	}
}
