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

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

		// Log the request
		console.log('Getting ARM config with parameters:', { groupNameOrGuidOrSerial });

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

		// Make API call
		const response = await apiRequest.call(this, 'GET', endpoint, {}, {});
		console.log('Received ARM config');

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

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

		// Parse the ARM Config JSON
		let armConfig: ArmConfig;
		try {
			armConfig = JSON.parse(armConfigJson);
		} catch (parseError) {
			throw new Error(`Invalid JSON format for ARM config: ${parseError.message}`);
		}

		// Log the request
		console.log('Updating ARM config:', { groupNameOrGuidOrSerial, armConfig });

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

		// Make API call
		const response = await apiRequest.call(this, 'POST', endpoint, armConfig as IDataObject, {});
		console.log('ARM config updated successfully');

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