import { IExecuteFunctions, INodeExecutionData } from 'n8n-workflow';
import { apiRequest } from '../../../../helpers/apiRequest';
import { logger } from '../../../../helpers/logger';
import { handleApiError } from '../../../../helpers/errorHandler';

/**
 * AI Insight Details for a Client
 *
 * GET /aiops/v2/insights/client/{sta_mac}/id/{insight_id}/export
 *
 * @param this The n8n execution context
 * @returns Formatted API response
 */
export async function getInsightDetailsClient(
	this: IExecuteFunctions,
): Promise<INodeExecutionData[]> {
	try {
		// Get parameters
		const staMac = this.getNodeParameter('sta_mac', 0) as string;
		const insightId = this.getNodeParameter('insight_id', 0) as number;
		const fromDate = new Date(this.getNodeParameter('from', 0) as string);
		const toDate = new Date(this.getNodeParameter('to', 0) as string);

		// Convert dates to epoch milliseconds for API
		const fromMs = fromDate.getTime();
		const toMs = toDate.getTime();

		logger.debug(
			'aiops:insightDetails:getInsightDetailsClient',
			`Getting details for client=${staMac}, insight=${insightId}, from=${fromMs}, to=${toMs}`,
		);

		// Construct query parameters
		const qs = {
			from: fromMs,
			to: toMs,
		};

		// Make API request
		const endpoint = `/aiops/v2/insights/client/${encodeURIComponent(staMac)}/id/${insightId}/export`;
		const responseData = await apiRequest.call(this, 'GET', endpoint, {}, qs);

		logger.debug(
			'aiops:insightDetails:getInsightDetailsClient',
			'Successfully retrieved client insight details',
		);

		// Return formatted response
		return [{ json: responseData }];
	} catch (error) {
		logger.error('aiops:insightDetails:getInsightDetailsClient:error', { message: error.message });
		return handleApiError.call(this, error, 'Failed to get AI insight details for client');
	}
}
