import { useQuery } from "@tanstack/react-query";
import { apiClient } from "@/lib/api";
import type { SearchResponse, SearchParams } from "../types";
import type {
  Product,
  PaginatedResponse,
  ProductFilters,
} from "@/lib/types/api";

export function useSearchProducts(params: SearchParams) {
  const { q, barcode } = params;

  return useQuery({
    queryKey: ["search", { q, barcode }],
    queryFn: async () => {
      if (barcode) {
        const response = await apiClient.get<SearchResponse>(
          `/search-product-barcode?barcode=${barcode}`,
        );
        return response.data;
      }

      if (q) {
        const response = await apiClient.get<SearchResponse>(
          `/search-product?q=${encodeURIComponent(q)}`,
        );
        return response.data;
      }

      return { message: "success", data: [] };
    },
    enabled: !!(q && q.length > 0) || !!barcode,
    staleTime: 1000 * 60 * 5,
  });
}

export function useFilteredSearchProducts(
  q: string,
  filters: ProductFilters,
  options?: { enabled?: boolean },
) {
  return useQuery({
    queryKey: ["search-filtered", q, filters],
    queryFn: async () => {
      const params: Record<string, any> = {
        q,
        page: filters.page || 1,
        per_page: filters.limit || 12,
      };

      if (filters.brands && filters.brands.length > 0) {
        params.brands = filters.brands.join(",");
      }

      if (filters.categories && filters.categories.length > 0) {
        params.categories = filters.categories.join(",");
      }

      if (filters.min_price !== undefined) {
        params.min_price = filters.min_price;
      }

      if (filters.max_price !== undefined) {
        params.max_price = filters.max_price;
      }

      const response = await apiClient.get<PaginatedResponse<Product>>(
        "/search-product",
        { params },
      );

      return {
        data: response.data.data || [],
        pagination: response.data.pagination || {},
      };
    },
    enabled: options?.enabled !== false && !!q,
  });
}
