'use client';

import { useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { validateOAuthState } from '@/lib/auth';
import { toast } from '@/hooks/use-toast';

export function OAuthCallbackHandler() {
  const searchParams = useSearchParams();
  const router = useRouter();
  
  useEffect(() => {
    // Check if this is an OAuth callback
    const state = searchParams.get('state');
    const session = searchParams.get('session');
    const userJson = searchParams.get('user');
    
    // If we have state and session, this might be an OAuth callback
    if (state && session) {
      // Validate the state parameter to prevent CSRF
      const isValid = validateOAuthState(state);
      
      if (!isValid) {
        // State validation failed, possible CSRF attack
        toast({
          title: 'Authentication Error',
          description: 'Security validation failed. Please try signing in again.',
          variant: 'destructive',
        });
        router.push('/login?error=invalid_state');
        return;
      }
      
      // State is valid, process the login
      if (userJson) {
        try {
          const user = JSON.parse(decodeURIComponent(userJson));
          
          // Store the user in session
          sessionStorage.setItem('currentUser', JSON.stringify(user));
          
          // Show success message
          toast({
            title: 'Signed in successfully',
            description: `Welcome ${user.name}!`,
          });
          
          // Remove the query parameters from the URL
          router.replace('/');
        } catch (error) {
          console.error('Failed to parse user data', error);
          toast({
            title: 'Authentication Error',
            description: 'Failed to process authentication data',
            variant: 'destructive',
          });
          router.push('/login?error=invalid_user_data');
        }
      }
    }
  }, [searchParams, router]);
  
  // This is a utility component that doesn't render anything
  return null;
} 