"use client";

import { useMutation, useQueryClient } from "@tanstack/react-query";
import { apiClient, getDataOrThrow, queryKeys } from "@/core/api";
import type {
  AddCaseCommentRequest,
  AddCaseCommentResponse,
} from "@customer-portal/domain/support";

/**
 * Hook to add a comment to a case (customer reply via portal)
 *
 * Creates a public CaseComment visible to both customer and agents.
 */
export function useAddCaseComment(caseId: string) {
  const queryClient = useQueryClient();

  return useMutation<AddCaseCommentResponse, Error, AddCaseCommentRequest>({
    mutationFn: async request => {
      const response = await apiClient.POST<AddCaseCommentResponse>(
        `/api/support/cases/${caseId}/comments`,
        { body: request }
      );
      return getDataOrThrow(response, "Failed to add comment");
    },
    onSuccess: () => {
      // Invalidate the messages query to refetch the conversation
      void queryClient.invalidateQueries({
        queryKey: [...queryKeys.support.case(caseId), "messages"],
      });
      // Also invalidate the case itself as it may have updated
      void queryClient.invalidateQueries({
        queryKey: queryKeys.support.case(caseId),
      });
    },
  });
}
