import { useQuery } from 'react-query';

import { type RequestError, type RequestSuccess } from 'src/types/services';
import { sToMs } from 'src/utils/timeUtils';

import { learningCertificatesKeys } from '../queries';
import { getLearningCertificate } from '../services';

type TSuccess = RequestSuccess<typeof getLearningCertificate>;
type TError = RequestError;
type TData = TSuccess['data'];

/** Fetches a single certificate by id. Disabled until an id is provided. */
export const useGetLearningCertificate = (certificateId?: number) =>
  useQuery<TSuccess, TError, TData>({
    queryKey: learningCertificatesKeys.detail(certificateId!),
    queryFn: () => {
      if (!certificateId)
        throw new Error(
          '[useGetLearningCertificate] Certificate ID is required',
        );
      return getLearningCertificate(certificateId);
    },
    select: response => response.data,
    staleTime: sToMs(60),
    enabled: !!certificateId,
  });
