import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { queryKeys } from "./keys";
import { entityOnboardingService } from "@/services/entity-onboarding.service";
import type { CredentialFilters } from "@/types";

export function useValidateCSV() {
  return useMutation({
    mutationFn: (file: File) => entityOnboardingService.validateCsv(file),
  });
}

export function useBulkCreate() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (payload: { validate_session_id?: string }) => entityOnboardingService.bulkCreate(payload),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["entity-onboarding"] });
    },
  });
}

export function useSendCredentials() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (studentIds: number[]) => entityOnboardingService.sendCredentials(studentIds),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: queryKeys.entityOnboarding.credentials() });
    },
  });
}

export function useCredentialStatuses(filters?: CredentialFilters & { page?: number; limit?: number }) {
  return useQuery({
    queryKey: queryKeys.entityOnboarding.credentials(filters as Record<string, unknown> | undefined),
    queryFn: () => entityOnboardingService.getCredentialStatuses(filters),
  });
}

export function useResendCredential() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (studentId: number) => entityOnboardingService.resendCredential(studentId),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["entity-onboarding", "credentials"] });
    },
  });
}

export function useResendAllPendingCredentials() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: () => entityOnboardingService.resendAllPending(),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: ["entity-onboarding", "credentials"] });
    },
  });
}
