/**
 * History Feed Store
 * Story 3.1: State management for history feed with pagination
 *
 * Architecture Compliance:
 * - Atomic selectors required for performance (do NOT destructure entire state)
 * - Service layer (DraftService) handles database queries
 * - Store manages loading state, pagination, and selected draft
 */

import { create } from 'zustand';
import { DraftService, type Draft } from '../db/draft-service';

const PAGE_SIZE = 20;

interface HistoryState {
  // Data
  drafts: Draft[];
  selectedDraft: Draft | null;

  // UI State
  loading: boolean;
  hasMore: boolean;
  error: string | null;

  // Actions
  loadMore: () => Promise<void>;
  refreshHistory: () => Promise<void>;
  selectDraft: (draft: Draft) => void;
  closeDetail: () => void;
  clearError: () => void;
  deleteDraft: (draftId: number) => Promise<boolean>;
}

export const useHistoryStore = create<HistoryState>((set, get) => ({
  // Initial state
  drafts: [],
  selectedDraft: null,
  loading: false,
  hasMore: true,
  error: null,

  /**
   * Delete a draft from history
   */
  deleteDraft: async (draftId: number) => {
    try {
      const success = await DraftService.deleteDraft(draftId);

      if (success) {
        set(state => ({
          drafts: state.drafts.filter(d => d.id !== draftId),
          // Close detail if the deleted draft was selected
          selectedDraft: state.selectedDraft?.id === draftId ? null : state.selectedDraft
        }));
      }
      return success;
    } catch (error) {
      set({
        error: error instanceof Error ? error.message : 'Failed to delete draft'
      });
      return false;
    }
  },

  /**
   * Load more drafts (pagination)
   * Appends to existing drafts for infinite scroll
   */
  loadMore: async () => {
    const { drafts, loading } = get();

    // Prevent duplicate loading
    if (loading) {
      return;
    }

    set({ loading: true, error: null });

    try {
      const newDrafts = await DraftService.getCompletedDrafts({
        limit: PAGE_SIZE,
        offset: drafts.length
      });

      set(state => ({
        drafts: [...state.drafts, ...newDrafts],
        hasMore: newDrafts.length === PAGE_SIZE,
        loading: false
      }));
    } catch (error) {
      set({
        error: error instanceof Error ? error.message : 'Failed to load history',
        loading: false
      });
    }
  },

  /**
   * Refresh history from database
   * Clears existing drafts and reloads from scratch
   */
  refreshHistory: async () => {
    set({ drafts: [], hasMore: true, error: null });
    await get().loadMore();
  },

  /**
   * Select a draft to view in detail sheet
   */
  selectDraft: (draft: Draft) => {
    set({ selectedDraft: draft });
  },

  /**
   * Close detail sheet
   */
  closeDetail: () => {
    set({ selectedDraft: null });
  },

  /**
   * Clear error state
   */
  clearError: () => {
    set({ error: null });
  }
}));
