"use client";

import { useMemo } from "react";
import { useQuery } from "@tanstack/react-query";
import { useAuthSession } from "@/features/auth/services/auth.store";
import { apiClient, getDataOrThrow, queryKeys } from "@/lib/api";
import type { SupportCaseFilter, SupportCaseList } from "@customer-portal/domain/support";

export function useSupportCases(filters?: SupportCaseFilter) {
  const { isAuthenticated } = useAuthSession();
  const queryFilters = useMemo(() => filters ?? {}, [filters]);

  return useQuery<SupportCaseList>({
    queryKey: queryKeys.support.cases(queryFilters),
    queryFn: async () => {
      const response = await apiClient.GET<SupportCaseList>("/api/support/cases", {
        params: Object.keys(queryFilters).length > 0 ? { query: queryFilters } : undefined,
      });
      return getDataOrThrow(response, "Failed to load support cases");
    },
    enabled: isAuthenticated,
    staleTime: 60 * 1000,
  });
}
