/* eslint-disable camelcase */
import React, { useEffect } from 'react';
import { useRouter } from 'next/router';

function CognitoAuth() {
  const router = useRouter();
  const { authUri, redirectUri, state, code, error, error_description } = router.query;

  useEffect(() => {
    if (authUri) {
      const { origin, pathname, searchParams } = new URL(decodeURIComponent(authUri));

      const authSearchParams = Object.fromEntries(searchParams);

      router.replace({
        pathname: `${origin}${pathname}`,
        query: {
          ...authSearchParams,
          state: redirectUri,
          redirect_uri: `${window.location.origin}/auth/cognito`,
        },
      });
    }

    if (code) {
      router.replace({
        pathname: decodeURIComponent(state),
        query: {
          code,
        },
      });
    }

    if (error) {
      router.replace({
        pathname: decodeURIComponent(state),
        query: {
          error: error_description,
        },
      });
    }
  }, []);

  // eslint-disable-next-line react/jsx-no-useless-fragment
  return <></>;
}

export default CognitoAuth;
