// src/client/processes/useNotificationNavigation.ts
// Process для обработки навигации по клику на уведомление

import { useRouter } from 'vue-router';
import { useNotificationStore } from '../entities/notification';
import type { Notification } from '../entities/notification';

export function useNotificationNavigation() {
  const router = useRouter();
  const notificationStore = useNotificationStore();

  async function handleClick(notification: Notification) {
    try {
      console.log('[NotificationNavigation] Notification clicked:', notification);
      console.log('[NotificationNavigation] Notification data:', notification.data);
      console.log('[NotificationNavigation] Notification link:', notification.data?.link);

      // Mark notification as read
      await notificationStore.markAsRead(notification.id);

      // Navigate to link if provided
      if (notification.data?.link) {
        const { path, query } = notification.data.link;

        // Конвертируем Proxy в обычный объект для Vue Router
        const queryObject = query ? JSON.parse(JSON.stringify(query)) : undefined;

        console.log('[NotificationNavigation] Navigating to:', { path, query: queryObject });

        if (path) {
          router.push({ path, query: queryObject });

          // Clear query parameters after modal opens (small delay to ensure modal renders)
          // This allows repeated clicks on the same notification to trigger new navigation
          setTimeout(() => {
            router.replace({ path, query: undefined });
          }, 100);
        }
      }
    } catch (error) {
      console.error('[NotificationNavigation] Failed to handle notification click:', error);
    }
  }

  return { handleClick };
}
