/**
 * useInvestmentProducts Hook
 * TanStack Query hook for fetching investment products
 * Epic: OQI-004 Cuentas de Inversion
 */

import { useQuery } from '@tanstack/react-query';
import {
  getProducts,
  getProductById,
  getProductPerformance,
  type Product,
  type ProductPerformance,
} from '../../../services/investment.service';

// ============================================================================
// Query Keys
// ============================================================================

export const investmentProductKeys = {
  all: ['investment-products'] as const,
  lists: () => [...investmentProductKeys.all, 'list'] as const,
  listByRisk: (riskProfile: string) =>
    [...investmentProductKeys.all, 'list', { riskProfile }] as const,
  detail: (id: string) => [...investmentProductKeys.all, 'detail', id] as const,
  performance: (id: string, period: string) =>
    [...investmentProductKeys.all, 'performance', id, period] as const,
};

// ============================================================================
// Hooks
// ============================================================================

/**
 * Hook to fetch all investment products
 */
export function useInvestmentProducts(riskProfile?: string) {
  return useQuery<Product[], Error>({
    queryKey: riskProfile
      ? investmentProductKeys.listByRisk(riskProfile)
      : investmentProductKeys.lists(),
    queryFn: () => getProducts(riskProfile),
    staleTime: 5 * 60 * 1000, // 5 minutes - products don't change often
  });
}

/**
 * Hook to fetch a single product by ID
 */
export function useProductDetail(productId: string) {
  return useQuery<Product, Error>({
    queryKey: investmentProductKeys.detail(productId),
    queryFn: () => getProductById(productId),
    enabled: !!productId,
    staleTime: 5 * 60 * 1000,
  });
}

/**
 * Hook to fetch product performance data
 */
export function useProductPerformance(
  productId: string,
  period: 'week' | 'month' | '3months' | 'year' = 'month'
) {
  return useQuery<ProductPerformance[], Error>({
    queryKey: investmentProductKeys.performance(productId, period),
    queryFn: () => getProductPerformance(productId, period),
    enabled: !!productId,
    staleTime: 60 * 1000, // 1 minute
  });
}

export default useInvestmentProducts;
