// src/client/processes/entitySync.ts
// Orchestrator for inter-entity synchronization (FSD Pattern)

import { watch } from 'vue';
import { useUserStore } from '@client/entities/user';
import { useNoteStore } from '@client/entities/note';
import { useNotificationStore } from '@client/entities/notification';
import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';

dayjs.extend(utc);

export function initEntitySync() {
  const userStore = useUserStore();
  const noteStore = useNoteStore();
  const notificationStore = useNotificationStore();

  // 1. Sync User ID to Note Store (Decouples Note from User)
  watch(() => userStore.user?.id, (newId) => {
    noteStore.setCurrentUserId(newId || null);
  }, { immediate: true });

  // 2. Sync Note 'markAsRead' to Notifications (Decouples Note from Notification)
  // Pinia $onAction allows intercepting actions from any component automatically
  noteStore.$onAction(({ name, args, after }) => {
    if (name === 'markAsRead') {
      after(() => {
        const noteId = args[0] as string;
        const timestamp = dayjs.utc().toISOString();

        // Гасим уведомления в NotificationStore
        const related = notificationStore.notifications
          .filter(n => n.data?.noteId === noteId && !n.readAt);

        related.forEach(n => {
          n.readAt = timestamp; // Оптимистичный UI
          notificationStore.markAsRead(n.id); // Фоновый API вызов
        });
      });
    }
  });
}
