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

export async function getIapVariables(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, 50) 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 = additionalOptions.limit;
			}
			if (additionalOptions.offset) {
				queryParams.offset = additionalOptions.offset;
			}
		}

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

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

		if (returnAll || limit) {
			// Use pagination helper with a custom batch size of 100 (conservative default)
			return await handlePagination.call(
				this,
				endpoint,
				'GET',
				{},
				queryParams,
				{
					path: ['variables'],
					fallbackPaths: [['data', 'variables']],
				},
				returnAll,
				limit,
				100, // Conservative batch size for iap_variables endpoint
			);
		} else {
			// Make a single API call without pagination
			const response = await apiRequest.call(this, 'GET', endpoint, {}, queryParams);
			console.log('Received IAP variables');
			return formatResponse.call(this, response);
		}
	} catch (error) {
		console.log('ERROR in getIapVariables:', error);
		throw error;
	}
}

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

		// Parse the IAP variables JSON
		let iapVariables: ApVariables;
		try {
			iapVariables = JSON.parse(iapVariablesJson);
		} catch (parseError) {
			throw new Error(`Invalid JSON format for IAP variables: ${parseError.message}`);
		}

		// Log the request
		console.log('Replacing IAP variables:', { groupNameOrGuidOrSerial, iapVariables });

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

		// Make API call
		const response = await apiRequest.call(this, 'POST', endpoint, iapVariables as IDataObject, {});
		console.log('IAP variables replaced successfully');

		return formatResponse.call(this, response);
	} catch (error) {
		console.log('ERROR in replaceIapVariables:', error);
		throw error;
	}
}
