// helpers/responseFormatter.ts
import { IExecuteFunctions, INodeExecutionData } from 'n8n-workflow';
import { logger } from './logger';

/**
 * Formats the API response into n8n node items
 *
 * @param response The API response to format
 * @returns Formatted array of node items
 */
export function formatResponse(response: any): INodeExecutionData[] {
	logger.debug('formatter:format', 'Formatting response');

	// If there's no response, return empty array
	if (!response) {
		logger.debug('formatter:format', 'No response data');
		return [{ json: { success: false, message: 'No data returned' } }];
	}

	// If response is null or not an object, return it directly
	if (response === null || typeof response !== 'object') {
		logger.debug('formatter:format', 'Response is not an object, returning directly');
		return [{ json: { data: response } }];
	}

	// For paginated responses with known properties
	if (response.count !== undefined) {
		logger.debug('formatter:format', `Paginated response with count: ${response.count}`);

		// Known data properties in Aruba Central API responses
		const possibleArrayProps = [
			'aps',
			'clients',
			'bssids',
			'samples',
			'trails',
			'devices',
			'switches',
			'gateways',
			'data',
			'results',
			'items',
		];

		// Try to find the data array
		for (const prop of possibleArrayProps) {
			if (Array.isArray(response[prop])) {
				const items = response[prop].map((item: any) => ({ json: item }));
				logger.debug('formatter:format', `Found ${items.length} items in property "${prop}"`);
				return items;
			}
		}

		// If no array property is found but we know it's paginated,
		// try to find any array in the response
		const anyArrayProp = Object.keys(response).find((key) => Array.isArray(response[key]));
		if (anyArrayProp) {
			const items = response[anyArrayProp].map((item: any) => ({ json: item }));
			logger.debug(
				'formatter:format',
				`Found ${items.length} items in detected array property "${anyArrayProp}"`,
			);
			return items;
		}
	}

	// For single entity responses
	const entityProps = ['ap', 'client', 'switch', 'gateway', 'device', 'data', 'result', 'item'];
	for (const prop of entityProps) {
		if (response[prop] !== undefined) {
			logger.debug('formatter:format', `Found single entity in property "${prop}"`);
			return [{ json: response[prop] }];
		}
	}

	// If the response is already an array
	if (Array.isArray(response)) {
		logger.debug('formatter:format', `Response is an array with ${response.length} items`);
		return response.map((item) => ({ json: item }));
	}

	// For responses with a data property containing the result
	if (response.data !== undefined) {
		if (Array.isArray(response.data)) {
			logger.debug(
				'formatter:format',
				`Found array in "data" property with ${response.data.length} items`,
			);
			return response.data.map((item: any) => ({ json: item }));
		} else if (typeof response.data === 'object' && response.data !== null) {
			logger.debug('formatter:format', 'Found object in "data" property');
			return [{ json: response.data }];
		}
	}

	// Default fallback - return the entire response
	logger.debug(
		'formatter:format',
		'Using default fallback, returning entire response as single item',
	);
	return [{ json: response }];
}
