import { mutationOptions } from '@tanstack/react-query';
import { getQueryClient } from '@/lib/query-client';
import { invalidateTrainingRecordData } from '@/lib/query-invalidation';
import { deleteCertificate, uploadCertificates } from './service';
import { trainingRecordKeys } from './queries';

export const uploadCertificatesMutation = mutationOptions({
  mutationFn: ({
    trainingRecordId,
    files
  }: {
    trainingRecordId: number;
    files: File[];
  }) => uploadCertificates(trainingRecordId, files),
  onSuccess: (_data, variables) => {
    const queryClient = getQueryClient();
    return Promise.all([
      invalidateTrainingRecordData(queryClient),
      queryClient.invalidateQueries({
        queryKey: trainingRecordKeys.certificates(variables.trainingRecordId)
      }),
      queryClient.invalidateQueries({
        queryKey: trainingRecordKeys.detail(variables.trainingRecordId)
      })
    ]);
  }
});

export const deleteCertificateMutation = mutationOptions({
  mutationFn: ({
    trainingRecordId,
    certificateId
  }: {
    trainingRecordId: number;
    certificateId: number;
  }) => deleteCertificate(trainingRecordId, certificateId),
  onSuccess: (_data, variables) => {
    const queryClient = getQueryClient();
    return Promise.all([
      invalidateTrainingRecordData(queryClient),
      queryClient.invalidateQueries({
        queryKey: trainingRecordKeys.certificates(variables.trainingRecordId)
      }),
      queryClient.invalidateQueries({
        queryKey: trainingRecordKeys.detail(variables.trainingRecordId)
      })
    ]);
  }
});
