/**
 * useProductDetail Hook
 * TanStack Query hooks for fetching product details by type
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { marketplaceService } from '../../../services/marketplace.service';
import type {
  SignalPack,
  AdvisoryService,
  CourseProduct,
  ProductReview,
  ProductCategory,
  PaginatedResponse,
} from '../../../types/marketplace.types';

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

export const productDetailKeys = {
  all: ['product-detail'] as const,
  signalPack: (idOrSlug: string) =>
    [...productDetailKeys.all, 'signals', idOrSlug] as const,
  advisory: (idOrSlug: string) =>
    [...productDetailKeys.all, 'advisory', idOrSlug] as const,
  course: (idOrSlug: string) =>
    [...productDetailKeys.all, 'courses', idOrSlug] as const,
  reviews: (productId: string, productType: ProductCategory) =>
    [...productDetailKeys.all, 'reviews', productType, productId] as const,
};

// ============================================================================
// Signal Pack Hooks
// ============================================================================

/**
 * Hook for fetching signal pack by ID
 */
export function useSignalPackById(id: string) {
  return useQuery<SignalPack, Error>({
    queryKey: productDetailKeys.signalPack(id),
    queryFn: () => marketplaceService.getSignalPackById(id),
    enabled: !!id,
    staleTime: 1000 * 60 * 5,
  });
}

/**
 * Hook for fetching signal pack by slug
 */
export function useSignalPackBySlug(slug: string) {
  return useQuery<SignalPack, Error>({
    queryKey: productDetailKeys.signalPack(slug),
    queryFn: () => marketplaceService.getSignalPackBySlug(slug),
    enabled: !!slug,
    staleTime: 1000 * 60 * 5,
  });
}

// ============================================================================
// Advisory Service Hooks
// ============================================================================

/**
 * Hook for fetching advisory service by ID
 */
export function useAdvisoryServiceById(id: string) {
  return useQuery<AdvisoryService, Error>({
    queryKey: productDetailKeys.advisory(id),
    queryFn: () => marketplaceService.getAdvisoryServiceById(id),
    enabled: !!id,
    staleTime: 1000 * 60 * 5,
  });
}

/**
 * Hook for fetching advisory service by slug
 */
export function useAdvisoryServiceBySlug(slug: string) {
  return useQuery<AdvisoryService, Error>({
    queryKey: productDetailKeys.advisory(slug),
    queryFn: () => marketplaceService.getAdvisoryServiceBySlug(slug),
    enabled: !!slug,
    staleTime: 1000 * 60 * 5,
  });
}

/**
 * Hook for fetching advisor availability
 */
export function useAdvisorAvailability(advisoryId: string, date: string) {
  return useQuery<{ slots: string[]; timezone: string }, Error>({
    queryKey: ['advisor-availability', advisoryId, date],
    queryFn: () => marketplaceService.getAdvisorAvailability(advisoryId, date),
    enabled: !!(advisoryId && date),
    staleTime: 1000 * 60 * 2, // 2 minutes - availability changes frequently
  });
}

// ============================================================================
// Course Product Hooks
// ============================================================================

/**
 * Hook for fetching course product by ID
 */
export function useCourseProductById(id: string) {
  return useQuery<CourseProduct, Error>({
    queryKey: productDetailKeys.course(id),
    queryFn: () => marketplaceService.getCourseProductById(id),
    enabled: !!id,
    staleTime: 1000 * 60 * 5,
  });
}

/**
 * Hook for fetching course product by slug
 */
export function useCourseProductBySlug(slug: string) {
  return useQuery<CourseProduct, Error>({
    queryKey: productDetailKeys.course(slug),
    queryFn: () => marketplaceService.getCourseProductBySlug(slug),
    enabled: !!slug,
    staleTime: 1000 * 60 * 5,
  });
}

// ============================================================================
// Reviews Hooks
// ============================================================================

interface ReviewsParams {
  page?: number;
  pageSize?: number;
  sortBy?: 'newest' | 'helpful' | 'rating';
}

/**
 * Hook for fetching product reviews
 */
export function useProductReviews(
  productId: string,
  productType: ProductCategory,
  params: ReviewsParams = {}
) {
  return useQuery<PaginatedResponse<ProductReview>, Error>({
    queryKey: [...productDetailKeys.reviews(productId, productType), params],
    queryFn: () => marketplaceService.getProductReviews(productId, productType, params),
    enabled: !!(productId && productType),
    staleTime: 1000 * 60 * 2,
  });
}

/**
 * Hook for creating a product review
 */
export function useCreateReview() {
  const queryClient = useQueryClient();

  return useMutation<
    ProductReview,
    Error,
    {
      productId: string;
      productType: ProductCategory;
      data: { rating: number; title?: string; comment: string };
    }
  >({
    mutationFn: ({ productId, productType, data }) =>
      marketplaceService.createReview(productId, productType, data),
    onSuccess: (_, variables) => {
      // Invalidate reviews cache
      queryClient.invalidateQueries({
        queryKey: productDetailKeys.reviews(variables.productId, variables.productType),
      });
    },
  });
}

/**
 * Hook for marking a review as helpful
 */
export function useMarkReviewHelpful() {
  const queryClient = useQueryClient();

  return useMutation<void, Error, { reviewId: string; productId: string; productType: ProductCategory }>({
    mutationFn: ({ reviewId }) => marketplaceService.markReviewHelpful(reviewId),
    onSuccess: (_, variables) => {
      // Invalidate reviews cache
      queryClient.invalidateQueries({
        queryKey: productDetailKeys.reviews(variables.productId, variables.productType),
      });
    },
  });
}
