-- OAuth User Synchronization
-- This migration adds functionality to automatically create user profiles when users sign up via OAuth

-- =============================================
-- 1. CREATE FUNCTION FOR OAUTH USER AUTO-PROFILE CREATION
-- =============================================

CREATE OR REPLACE FUNCTION public.handle_new_oauth_user()
RETURNS TRIGGER AS $$
BEGIN
  -- Check if user profile already exists
  IF NOT EXISTS (
    SELECT 1 FROM public.user_profiles WHERE id = NEW.id
  ) THEN
    -- Create user profile with default active status
    INSERT INTO public.user_profiles (id, email, status)
    VALUES (
      NEW.id,
      NEW.email,
      'active'
    )
    ON CONFLICT (id) DO NOTHING;
  END IF;
  
  RETURN NEW;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- =============================================
-- 2. CREATE TRIGGER FOR NEW AUTH USERS
-- =============================================

-- Drop the trigger if it exists to avoid conflicts
DROP TRIGGER IF EXISTS on_auth_user_created ON auth.users;

-- Create trigger that fires after a new user is created in auth.users
CREATE TRIGGER on_auth_user_created
  AFTER INSERT ON auth.users
  FOR EACH ROW EXECUTE FUNCTION public.handle_new_oauth_user();

-- =============================================
-- 3. COMMENT FOR DOCUMENTATION
-- =============================================

COMMENT ON FUNCTION public.handle_new_oauth_user() IS 
'Automatically creates a user profile in public.user_profiles when a new user is created via OAuth in auth.users. This ensures OAuth users are immediately accessible in the application without manual provisioning.';
