'use client';

import { create } from 'zustand';
import { api } from '@/lib/api';
import { countUnreadNotifications, sortNotificationsNewestFirst, type NotificationRecord } from '@/lib/notification';

interface NotificationState {
  notifications: NotificationRecord[];
  loading: boolean;
  loadedFor?: string;
  unreadCount: number;
  fetchNotifications: (recipientId: string, options?: { unreadOnly?: boolean }) => Promise<void>;
  markRead: (id: string, recipientId: string) => Promise<void>;
  markAllRead: (recipientId: string) => Promise<void>;
}

export const useNotificationStore = create<NotificationState>((set, get) => ({
  notifications: [],
  loading: false,
  loadedFor: undefined,
  unreadCount: 0,

  fetchNotifications: async (recipientId, options) => {
    if (!recipientId) return;
    set({ loading: true });
    const params = new URLSearchParams({ recipientId });
    if (options?.unreadOnly) params.set('unreadOnly', 'true');
    const rows = await api.get<NotificationRecord[]>(`/notifications?${params.toString()}`);
    const notifications = sortNotificationsNewestFirst(rows);
    set({
      notifications,
      unreadCount: countUnreadNotifications(notifications),
      loadedFor: recipientId,
      loading: false,
    });
  },

  markRead: async (id, recipientId) => {
    await api.patch(`/notifications/${id}/read`, { recipientId });
    const notifications = get().notifications.map((item) =>
      item.id === id ? { ...item, readAt: item.readAt ?? new Date().toISOString() } : item,
    );
    set({ notifications, unreadCount: countUnreadNotifications(notifications) });
  },

  markAllRead: async (recipientId) => {
    await api.patch('/notifications/read-all', { recipientId });
    const readAt = new Date().toISOString();
    const notifications = get().notifications.map((item) => item.readAt ? item : { ...item, readAt });
    set({ notifications, unreadCount: 0 });
  },
}));
