// methods/configuration/ap/apCli.methods.ts
import { IExecuteFunctions, INodeExecutionData, IDataObject } from 'n8n-workflow';
import { apiRequest } from '../../../helpers/apiRequest';
import { formatResponse } from '../../../helpers/responseFormatter';
import { CliConfig } from './apConfiguration.types';

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

		// Build query parameters
		const queryParams: IDataObject = {};
		if (version) {
			queryParams.version = version;
		}

		// Log the request
		console.log('Getting AP CLI configuration with parameters:', {
			groupNameOrGuidOrSerial,
			version,
		});

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

		// Make API call
		const response = await apiRequest.call(this, 'GET', endpoint, {}, queryParams);
		console.log('Received AP CLI configuration');

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

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

		// Parse the CLI commands JSON
		let cliCommands: CliConfig;
		try {
			cliCommands = JSON.parse(cliCommandsJson);
		} catch (parseError) {
			throw new Error(`Invalid JSON format for CLI commands: ${parseError.message}`);
		}

		// Log the request
		console.log('Replacing AP CLI configuration:', { groupNameOrGuidOrSerial, cliCommands });

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

		// Make API call
		const response = await apiRequest.call(this, 'POST', endpoint, cliCommands as IDataObject, {});
		console.log('AP CLI configuration replaced successfully');

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