"use client";

import { useQuery } from "@tanstack/react-query";
import { useAuthSession } from "@/features/auth/stores/auth.store";
import { apiClient, getDataOrThrow, queryKeys } from "@/core/api";
import type { CaseMessageList } from "@customer-portal/domain/support";

/**
 * Hook to fetch messages for a case (conversation view)
 *
 * Returns a unified timeline of EmailMessages and public CaseComments.
 */
export function useCaseMessages(caseId: string | undefined) {
  const { isAuthenticated } = useAuthSession();

  return useQuery<CaseMessageList>({
    queryKey: [...queryKeys.support.case(caseId ?? ""), "messages"],
    queryFn: async () => {
      const response = await apiClient.GET<CaseMessageList>(
        `/api/support/cases/${caseId}/messages`
      );
      return getDataOrThrow(response, "Failed to load case messages");
    },
    enabled: isAuthenticated && !!caseId,
    // Refetch more frequently for active conversations
    refetchInterval: 30000, // 30 seconds
    staleTime: 10000, // 10 seconds
  });
}
