import { NotificationChannel, DeliveryStatus } from '../types';

/**
 * Notification delivery helper functions
 * Provides utilities for tracking and formatting delivery attempts
 */

export interface DeliveryAttempt {
	channel: NotificationChannel;
	recipientId: string;
	timestamp: Date;
	status: DeliveryStatus;
	retryCount?: number;
	errorMessage?: string;
}

/**
 * Format delivery result for consistent response
 */
export function formatDeliveryResult(
	channel: NotificationChannel,
	status: DeliveryStatus,
	recipientId: string,
	options?: { errorMessage?: string; retryCount?: number },
): DeliveryAttempt {
	return {
		channel,
		recipientId,
		timestamp: new Date(),
		status,
		retryCount: options?.retryCount ?? 0,
		...(options?.errorMessage !== undefined && { errorMessage: options.errorMessage }),
	};
}

/**
 * Check if delivery should be retried
 */
export function shouldRetryDelivery(status: DeliveryStatus, retryCount: number, maxRetries = 3): boolean {
	return status === 'failed' && retryCount < maxRetries;
}

/**
 * Get next retry delay with exponential backoff
 */
export function getRetryDelay(retryCount: number, baseDelayMs = 1000): number {
	return baseDelayMs * Math.pow(2, retryCount);
}

/**
 * Determine delivery channel priority
 */
export function getChannelPriority(channel: NotificationChannel): number {
	const priorities: Record<NotificationChannel, number> = {
		in_app: 1,
		push: 2,
		email: 3,
		sms: 4,
		zalo: 5,
	};
	return priorities[channel] ?? 99;
}

export const deliveryHelper = {
	formatDeliveryResult,
	shouldRetryDelivery,
	getRetryDelay,
	getChannelPriority,
};
