import { useNavigate } from 'react-router';

import OktaAuth, { toRelativeUrl } from '@okta/okta-auth-js';
import { Security as OktaSecurityProvider } from '@okta/okta-react';

import { OKTA_CONFIG } from 'src/config/okta';

const oktaAuth = new OktaAuth(OKTA_CONFIG);

export const OktaProvider = ({ children }: { children: React.ReactNode }) => {
  const navigate = useNavigate();

  const restoreOriginalUri = (_: OktaAuth, originalUri: string) => {
    const relativeUrl = toRelativeUrl(
      originalUri || '/',
      window.location.origin,
    );
    navigate(relativeUrl, { replace: true });
  };

  return (
    <OktaSecurityProvider
      oktaAuth={oktaAuth}
      restoreOriginalUri={restoreOriginalUri}
    >
      {children}
    </OktaSecurityProvider>
  );
};
