'use client';

import { useEffect } from 'react';

import { useRouter } from 'next/navigation';

import Loading from '@/app/home/loading';
import { getSupabaseBrowserClient } from '@/packages/supabase/src/clients/browser-client';

export function SignInPageClientRedirect() {
  const router = useRouter();

  useEffect(() => {
    async function signIn() {
      const { data, error } =
        await getSupabaseBrowserClient().auth.signInWithOAuth({
          provider: 'keycloak',
          options: {
            redirectTo: `${window.location.origin}/auth/callback`,
            queryParams: {
              prompt: 'login',
            },
          },
        });

      if (error) {
        console.error('OAuth error', error);
        router.push('/');
      } else if (data.url) {
        router.push(data.url);
      }
    }

    signIn();
  }, [router]);

  return <Loading />;
}
