import { format, formatDistanceToNow } from "date-fns"
import { ru } from "date-fns/locale"

export function formatDate(date: string | Date, pattern = "dd.MM.yyyy"): string {
	return format(new Date(date), pattern, { locale: ru })
}

export function formatRelativeTime(date: string | Date | null): string {
	if (!date) return ""
	return formatDistanceToNow(new Date(date), { addSuffix: true, locale: ru })
}

interface NotificationRelativeTimeOptions {
	now?: Date
}

export function formatNotificationRelativeTime(
	date: string | Date | null,
	options: NotificationRelativeTimeOptions = {},
): string {
	if (!date) return ""

	const targetDate = new Date(date)

	if (Number.isNaN(targetDate.getTime())) return ""

	const now = options.now ?? new Date()
	const diffMs = Math.max(0, now.getTime() - targetDate.getTime())
	const diffMinutes = Math.floor(diffMs / (1000 * 60))

	if (diffMinutes < 1) return "только что"
	if (diffMinutes < 60) return `${diffMinutes}мин`

	const diffHours = Math.floor(diffMinutes / 60)
	if (diffHours < 24) return `${diffHours}ч`

	const diffDays = Math.floor(diffHours / 24)
	if (diffDays < 7) return `${diffDays}д`

	return `${Math.floor(diffDays / 7)}нед`
}
