/**
 * OfflineStore
 *
 * Story 3.3: Zustand store for offline/sync status management
 *
 * Architecture Compliance:
 * - Uses atomic selectors pattern to prevent unnecessary re-renders
 * - State is separate from other stores (chat, history)
 * - Provides actions for network status and sync management
 */

import { create } from 'zustand';
import { db } from '../db';
import { SyncManager } from '../../services/sync-manager';

/**
 * Offline state interface
 */
interface OfflineState {
  isOnline: boolean;
  pendingCount: number;
  lastSyncAt: number | null;
  syncing: boolean;

  // Actions
  setOnlineStatus: (isOnline: boolean) => void;
  syncNow: () => Promise<void>;
  updatePendingCount: () => Promise<void>;
}

/**
 * Offline store
 *
 * Manages the offline/sync state of the application.
 * Tracks network status, pending sync items, and sync progress.
 */
export const useOfflineStore = create<OfflineState>((set, get) => ({
  // Initial state
  isOnline: typeof navigator !== 'undefined' ? navigator.onLine : true,
  pendingCount: 0,
  lastSyncAt: null,
  syncing: false,

  /**
   * Update online status
   * When going online, triggers pending count update
   */
  setOnlineStatus: (isOnline: boolean) => {
    set({ isOnline });

    // Update pending count when going online
    if (isOnline) {
      get().updatePendingCount();
    }
  },

  /**
   * Manually trigger sync now
   * Processes the queue and updates pending count
   */
  syncNow: async () => {
    set({ syncing: true });

    try {
      await SyncManager.processQueue();
      await get().updatePendingCount();
      set({ lastSyncAt: Date.now() });
    } finally {
      set({ syncing: false });
    }
  },

  /**
   * Update the count of pending sync items
   * Queries the syncQueue table for pending items
   */
  updatePendingCount: async () => {
    const count = await db.syncQueue.where('status').equals('pending').count();
    set({ pendingCount: count });
  },
}));
