import { useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';

type TupleToObject<T extends readonly string[]> = {
  [K in T[number]]: string;
};

function useRequiredParams<const T extends readonly string[]>(
  requiredParams: T,
  redirectTo: string | -1 = '/',
): TupleToObject<T> {
  const params = useParams();
  const navigate = useNavigate();

  useEffect(() => {
    for (const param of requiredParams) {
      const value = params[param];
      if (typeof value !== 'string') {
        if (redirectTo === -1) {
          navigate(-1);
        } else {
          navigate(redirectTo);
        }
        return;
      }
    }
  }, [params, requiredParams, navigate, redirectTo]);

  return params as TupleToObject<T>;
}

export default useRequiredParams;
