import { NotificationType } from '../types';

/**
 * Notification template helper functions
 * Provides utilities for message templating and formatting
 */

export interface NotificationTemplate {
	title: string;
	body: string;
	data?: Record<string, unknown>;
}

/**
 * Template variables that can be replaced in notifications
 */
export type TemplateVariables = Record<string, string | number | boolean>;

/**
 * Replace template variables in a string
 * Example: "Hello {{name}}" with { name: "John" } -> "Hello John"
 */
export function replaceTemplateVariables(template: string, variables: TemplateVariables): string {
	return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
		const value = variables[key];
		return value !== undefined ? String(value) : match;
	});
}

/**
 * Apply template variables to notification template
 */
export function applyTemplate(template: NotificationTemplate, variables: TemplateVariables): NotificationTemplate {
	return {
		title: replaceTemplateVariables(template.title, variables),
		body: replaceTemplateVariables(template.body, variables),
		...(template.data !== undefined && { data: template.data }),
	};
}

/**
 * Truncate message to max length with ellipsis
 */
export function truncateMessage(message: string, maxLength = 100): string {
	if (message.length <= maxLength) return message;
	return message.substring(0, maxLength - 3) + '...';
}

/**
 * Get default templates by notification type
 */
export function getDefaultTemplate(type: NotificationType): NotificationTemplate {
	const templates: Record<NotificationType, NotificationTemplate> = {
		system_alert: {
			title: 'System Notification',
			body: 'You have a new system notification.',
		},
		security_alert: {
			title: 'Security Alert',
			body: 'A security-related event has occurred.',
		},
		order_created: {
			title: 'Order Created',
			body: 'Your order has been created.',
		},
		order_shipped: {
			title: 'Order Shipped',
			body: 'Your order has been shipped.',
		},
		order_delivered: {
			title: 'Order Delivered',
			body: 'Your order has been delivered.',
		},
		payment_success: {
			title: 'Payment Successful',
			body: 'Your payment was successful.',
		},
		payment_failed: {
			title: 'Payment Failed',
			body: 'Your payment has failed.',
		},
		promotion: {
			title: 'Special Offer',
			body: 'Check out our latest offers!',
		},
		chat_message: {
			title: 'New Message',
			body: 'You have a new message.',
		},
		account_update: {
			title: 'Account Update',
			body: 'Your account has been updated.',
		},
	};

	return templates[type] ?? templates.system_alert;
}

export const templateHelper = {
	replaceTemplateVariables,
	applyTemplate,
	truncateMessage,
	getDefaultTemplate,
};
