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

/**
 * Formats the API response into n8n node items
 */
export function formatResponse(this: IExecuteFunctions, response: any): INodeExecutionData[] {
	console.log('Formatting response');

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

	// If result is an array with a known structure (paginated results)
	if (response && typeof response === 'object' && !Array.isArray(response)) {
		// For paginated responses with count property
		if (response.count !== undefined) {
			let items: INodeExecutionData[] = [];

			// Check various possible array locations
			const possibleArrayProps = ['aps', 'clients', 'bssids', 'samples', 'trails'];

			for (const prop of possibleArrayProps) {
				if (Array.isArray(response[prop])) {
					items = response[prop].map((item: any) => ({ json: item }));
					break;
				}
			}

			// If we found items through known properties
			if (items.length > 0) {
				return items;
			}
		}

		// For single entity responses
		if (response.ap) {
			return [{ json: response.ap }];
		}

		if (response.client) {
			return [{ json: response.client }];
		}
	}

	// If the response is already an array
	if (Array.isArray(response)) {
		return response.map((item) => ({ json: item }));
	}

	// Default fallback - return the entire response
	return [{ json: response }];
}
