# Library Store Domain Data Audit

**Date**: 2025-01-27  
**Action**: 4.1.2.2 - Audit library store for all domain data  
**Status**: ✅ Complete

## Summary

This audit lists all fields in the Library Store (`apps/web/src/stores/library.ts`) and categorizes them as domain data or UI state.

## Store Structure

### LibraryState Interface

```typescript
export interface LibraryState {
  items: NormalizedState<LibraryItem>;
  favorites: NormalizedState<LibraryItem>;
  isLoading: boolean;
  error: ApiError | null;
  pagination: {
    page: number;
    limit: number;
    total: number;
    hasNext: boolean;
    hasPrev: boolean;
  };
  filters: {
    type?: string;
    search?: string;
  };
}
```

## Field Analysis

### Domain Data Fields (from API/Backend)

1. **`items: NormalizedState<LibraryItem>`**
   - **Type**: Normalized state structure containing library items (tracks)
   - **Source**: Fetched from API via `fetchItems()` → `/tracks` endpoint
   - **Structure**: `{ byId: Record<string, LibraryItem>, allIds: string[] }`
   - **Purpose**: Stores the actual track/library item data from the backend
   - **Category**: ✅ **DOMAIN DATA**
   - **Migration**: Should migrate to React Query `useLibraryItems()` hook

2. **`favorites: NormalizedState<LibraryItem>`**
   - **Type**: Normalized state structure containing favorite items
   - **Source**: Fetched from API via `fetchFavorites()` → `/tracks?type=favorites` endpoint
   - **Structure**: `{ byId: Record<string, LibraryItem>, allIds: string[] }`
   - **Purpose**: Stores favorite tracks/library items from the backend
   - **Category**: ✅ **DOMAIN DATA**
   - **Migration**: Should migrate to React Query `useLibraryFavorites()` hook

3. **`pagination: { page, limit, total, hasNext, hasPrev }`**
   - **Type**: Pagination metadata object
   - **Source**: Returned from API responses (`PaginatedResponse<LibraryItem>`)
   - **Fields**:
     - `page: number` - Current page number
     - `limit: number` - Items per page
     - `total: number` - Total number of items
     - `hasNext: boolean` - Whether there's a next page
     - `hasPrev: boolean` - Whether there's a previous page
   - **Purpose**: Metadata about the paginated items list
   - **Category**: ✅ **DOMAIN DATA** (metadata about domain data)
   - **Migration**: Should be part of React Query pagination response

### UI State Fields (client-side only)

4. **`isLoading: boolean`**
   - **Type**: Boolean flag
   - **Source**: Set manually by actions (`setLoading()`, `fetchItems()`, etc.)
   - **Purpose**: Indicates whether an API request is in progress
   - **Category**: ✅ **UI STATE**
   - **Migration**: React Query handles this automatically (`isLoading`, `isFetching`)

5. **`error: ApiError | null`**
   - **Type**: Error object or null
   - **Source**: Set by error handlers (`setError()`, catch blocks)
   - **Purpose**: Stores error information for display to user
   - **Category**: ✅ **UI STATE**
   - **Migration**: React Query handles this automatically (`error`)

6. **`filters: { type?, search? }`**
   - **Type**: Filter preferences object
   - **Source**: Set by user via `setFilters()` action
   - **Fields**:
     - `type?: string` - Filter by item type
     - `search?: string` - Search query string
   - **Purpose**: User's filter/search preferences (persisted in localStorage)
   - **Category**: ✅ **UI STATE**
   - **Migration**: Should remain in Zustand store (user preferences)

## Actions Analysis

### Domain Data Actions

1. **`fetchItems(params?)`**
   - **Purpose**: Fetches library items from API
   - **Updates**: `items`, `pagination`, `isLoading`, `error`
   - **Category**: ✅ **DOMAIN DATA ACTION**
   - **Migration**: Replace with React Query `useQuery(['libraryItems', params])`

2. **`fetchFavorites()`**
   - **Purpose**: Fetches favorite items from API
   - **Updates**: `favorites`, `isLoading`, `error`
   - **Category**: ✅ **DOMAIN DATA ACTION**
   - **Migration**: Replace with React Query `useQuery(['libraryFavorites'])`

3. **`uploadFile(file, metadata)`**
   - **Purpose**: Uploads a new file/track
   - **Updates**: `items` (adds new item), `isLoading`, `error`
   - **Category**: ✅ **DOMAIN DATA ACTION**
   - **Migration**: Replace with React Query `useMutation()` with optimistic update

4. **`toggleFavorite(itemId)`**
   - **Purpose**: Toggles favorite status of an item
   - **Updates**: `items`, `favorites` (optimistic update), `error`
   - **Category**: ✅ **DOMAIN DATA ACTION**
   - **Migration**: Replace with React Query `useMutation()` with optimistic update

5. **`deleteItem(itemId)`**
   - **Purpose**: Deletes an item
   - **Updates**: `items`, `favorites` (optimistic update), `error`
   - **Category**: ✅ **DOMAIN DATA ACTION**
   - **Migration**: Replace with React Query `useMutation()` with optimistic update

6. **`clearItems()`**
   - **Purpose**: Clears all items and favorites
   - **Updates**: `items`, `favorites`, `pagination`
   - **Category**: ✅ **DOMAIN DATA ACTION**
   - **Migration**: Replace with React Query `queryClient.invalidateQueries()`

### UI State Actions

7. **`setFilters(filters)`**
   - **Purpose**: Updates filter preferences
   - **Updates**: `filters`, triggers `fetchItems()` (side effect)
   - **Category**: ✅ **UI STATE ACTION**
   - **Migration**: Should remain in Zustand store, but trigger React Query refetch

8. **`setLoading(loading)`**
   - **Purpose**: Manually sets loading state
   - **Updates**: `isLoading`
   - **Category**: ✅ **UI STATE ACTION**
   - **Migration**: Remove (React Query handles this)

9. **`setError(error)`**
   - **Purpose**: Manually sets error state
   - **Updates**: `error`
   - **Category**: ✅ **UI STATE ACTION**
   - **Migration**: Remove (React Query handles this)

## Middleware Usage

1. **`undoRedo()` middleware**
   - **Purpose**: Provides undo/redo functionality
   - **Tracks**: Changes to `items` and `favorites` (domain data)
   - **Category**: ✅ **DOMAIN DATA MIDDLEWARE**
   - **Migration**: Remove after domain data migration (React Query handles history)

2. **`stateMiddleware()` middleware**
   - **Purpose**: Logging, analytics, error handling
   - **Category**: ✅ **UTILITY MIDDLEWARE**
   - **Migration**: Remove after domain data migration (React Query has built-in logging)

3. **`stateNormalization` utilities**
   - **Purpose**: Normalize state structure (`normalize`, `addToNormalized`, etc.)
   - **Used for**: `items` and `favorites` (domain data)
   - **Category**: ✅ **DOMAIN DATA UTILITY**
   - **Migration**: Remove after domain data migration (React Query handles normalization)

4. **`persist()` middleware**
   - **Purpose**: Persist state to localStorage
   - **Persists**: `favorites` and `filters` only
   - **Category**: ✅ **MIXED** (persists both domain data and UI state)
   - **Migration**:
     - `favorites` → React Query persistence
     - `filters` → Keep in Zustand (UI state)

## Summary

### Domain Data Fields (3)

- `items` - Library items/tracks
- `favorites` - Favorite items
- `pagination` - Pagination metadata

### UI State Fields (3)

- `isLoading` - Loading indicator
- `error` - Error display
- `filters` - User filter preferences

### Domain Data Actions (6)

- `fetchItems()` - Fetch items
- `fetchFavorites()` - Fetch favorites
- `uploadFile()` - Upload new item
- `toggleFavorite()` - Toggle favorite
- `deleteItem()` - Delete item
- `clearItems()` - Clear all items

### UI State Actions (3)

- `setFilters()` - Update filters
- `setLoading()` - Set loading (obsolete after migration)
- `setError()` - Set error (obsolete after migration)

## Migration Plan

1. **Create React Query hooks**:
   - `useLibraryItems(params)` - For items list
   - `useLibraryFavorites()` - For favorites
   - `useLibraryItem(id)` - For single item (if needed)

2. **Create React Query mutations**:
   - `useUploadFile()` - Upload mutation
   - `useToggleFavorite()` - Toggle favorite mutation
   - `useDeleteItem()` - Delete mutation

3. **Keep in Zustand**:
   - `filters` - User preferences (UI state)

4. **Remove from Zustand**:
   - `items` - Migrate to React Query
   - `favorites` - Migrate to React Query
   - `pagination` - Part of React Query response
   - `isLoading` - React Query handles this
   - `error` - React Query handles this

5. **Remove middleware**:
   - `undoRedo()` - No longer needed
   - `stateMiddleware()` - No longer needed
   - `stateNormalization` utilities - No longer needed

## Next Steps

- **Action 4.1.2.3**: Determine which fields are UI state vs domain data (this audit)
- **Action 4.1.2.4**: Remove domain data from library store
- **Action 4.1.2.5**: Remove undoRedo middleware
- **Action 4.1.2.6**: Remove stateNormalization
- **Action 4.1.2.7**: Remove stateMiddleware
- **Action 4.1.2.8**: Update all components using library store domain data
