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

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

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

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

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

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

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

		// Parse the System Config JSON
		let systemConfig: SystemConfig;
		try {
			systemConfig = JSON.parse(systemConfigJson);
		} catch (parseError) {
			throw new Error(`Invalid JSON format for system config: ${parseError.message}`);
		}

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

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

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

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