/**
 * React Query hooks for library items
 *
 * These hooks replace the Zustand store's domain data fetching functionality.
 * They use React Query for caching, automatic refetching, and state management.
 *
 * Migration from: apps/web/src/stores/library.ts
 * - fetchItems() → useLibraryItems()
 * - fetchFavorites() → useLibraryFavorites()
 */

import { useQuery } from '@tanstack/react-query';
import { apiClient } from '@/services/api/client';
import type { LibraryItem, PaginatedResponse } from '@/types';

/**
 * Query key factory for library items
 */
export const libraryQueryKeys = {
  all: ['library'] as const,
  items: (params?: LibraryItemsParams) =>
    [...libraryQueryKeys.all, 'items', params] as const,
  favorites: () => [...libraryQueryKeys.all, 'favorites'] as const,
};

/**
 * Parameters for fetching library items
 */
export interface LibraryItemsParams {
  page?: number;
  limit?: number;
  type?: string;
  search?: string;
}

/**
 * Response structure matching the store's expectations
 */
export interface LibraryItemsResponse extends PaginatedResponse<LibraryItem> {
  page: number;
  limit: number;
  total: number;
  has_next: boolean;
  has_prev: boolean;
  items: LibraryItem[];
}

/**
 * Fetch library items from the API
 * Matches the store's fetchItems() functionality
 */
async function fetchLibraryItems(
  params: LibraryItemsParams = {},
): Promise<LibraryItemsResponse> {
  const { page = 1, limit = 20, type, search } = params;

  const response = await apiClient.get<LibraryItemsResponse>('/tracks', {
    params: {
      page,
      limit,
      type,
      search,
    },
  });

  const data = response.data;

  // Handle different response formats (matching store logic)
  const itemsArray = Array.isArray(data.items)
    ? data.items
    : Array.isArray(data)
      ? data
      : [];

  // Return normalized response structure
  return {
    ...data,
    items: itemsArray,
    page: data.page || page,
    limit: data.limit || limit,
    total: data.total || 0,
    has_next: data.has_next ?? false,
    has_prev: data.has_prev ?? false,
  };
}

/**
 * Fetch favorites from the API
 * Matches the store's fetchFavorites() functionality
 */
async function fetchLibraryFavorites(): Promise<LibraryItem[]> {
  const response = await apiClient.get<PaginatedResponse<LibraryItem>>(
    '/tracks',
    {
      params: {
        page: 1,
        limit: 100,
        type: 'favorites',
      },
    },
  );

  const data = response.data;

  // Handle different response formats (matching store logic)
  const favoritesArray = Array.isArray(data.items)
    ? data.items
    : Array.isArray(data)
      ? data
      : [];

  return favoritesArray;
}

/**
 * React Query hook for fetching library items
 *
 * Replaces: useLibraryStore().fetchItems()
 *
 * @example
 * ```tsx
 * const { data, isLoading, error } = useLibraryItems({ page: 1, limit: 20 });
 * ```
 */
export function useLibraryItems(params: LibraryItemsParams = {}) {
  return useQuery({
    queryKey: libraryQueryKeys.items(params),
    queryFn: () => fetchLibraryItems(params),
    staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes
    gcTime: 10 * 60 * 1000, // Keep in cache for 10 minutes
  });
}

/**
 * React Query hook for fetching favorites
 *
 * Replaces: useLibraryStore().fetchFavorites()
 *
 * @example
 * ```tsx
 * const { data: favorites, isLoading, error } = useLibraryFavorites();
 * ```
 */
export function useLibraryFavorites() {
  return useQuery({
    queryKey: libraryQueryKeys.favorites(),
    queryFn: fetchLibraryFavorites,
    staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes
    gcTime: 10 * 60 * 1000, // Keep in cache for 10 minutes
  });
}
