// ArubaCentral/methods/configuration/ap/dirtyDiff.methods.ts
import { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow';
import { apiRequest } from '../../../helpers/apiRequest';
import { formatResponse } from '../../../helpers/responseFormatter';
import { handlePagination } from '../../../helpers/pagination';

export async function getDirtyDiff(this: IExecuteFunctions): Promise<INodeExecutionData[]> {
	try {
		// Get parameters
		const groupNameOrGuidOrSerial = this.getNodeParameter('groupNameOrGuidOrSerial', 0) as string;
		const returnAll = this.getNodeParameter('returnAll', 0, false) as boolean;

		let limit: number | undefined;
		if (!returnAll) {
			limit = this.getNodeParameter('limit', 0, 20) as number;
		}

		const additionalOptions = this.getNodeParameter('additionalOptions', 0, {}) as {
			limit?: number;
			offset?: number;
		};

		// Build query parameters
		const queryParams: IDataObject = {};

		// Use additionalOptions only if not using returnAll/limit
		if (!returnAll && !limit) {
			if (additionalOptions.limit) {
				queryParams.limit = Math.min(additionalOptions.limit, 20); // Ensure max 20
			}
			if (additionalOptions.offset) {
				queryParams.offset = additionalOptions.offset;
			}
		}

		// Log the request
		console.log('Getting dirty diff with parameters:', {
			groupNameOrGuidOrSerial,
			returnAll,
			limit,
			additionalOptions,
		});

		// Build the endpoint
		const endpoint = `/configuration/v1/dirty_diff/${groupNameOrGuidOrSerial}`;

		if (returnAll || limit) {
			// Use pagination helper with a custom batch size of 20
			return await handlePagination.call(
				this,
				endpoint,
				'GET',
				{},
				queryParams,
				{
					path: ['dirty_diff_list'],
					fallbackPaths: [['data', 'dirty_diff_list']],
				},
				returnAll,
				limit,
				20, // Custom batch size for dirty_diff endpoint
			);
		} else {
			// Make a single API call without pagination
			const response = await apiRequest.call(this, 'GET', endpoint, {}, queryParams);
			console.log('Received dirty diff');
			return formatResponse.call(this, response);
		}
	} catch (error) {
		console.log('ERROR in getDirtyDiff:', error);
		throw error;
	}
}
