-- ============================================================================
-- OrbiQuant IA - Trading Platform
-- Schema: auth
-- File: functions/04-create_user_profile_trigger.sql
-- Description: Automatically create user profile when new user is created
-- ============================================================================

CREATE OR REPLACE FUNCTION auth.create_user_profile()
RETURNS TRIGGER AS $$
BEGIN
  -- Create a new user profile for the newly created user
  INSERT INTO auth.user_profiles (
    user_id,
    language,
    timezone,
    newsletter_subscribed,
    marketing_emails_enabled,
    notifications_enabled,
    created_at,
    updated_at
  ) VALUES (
    NEW.id,
    'en',
    'UTC',
    false,
    false,
    true,
    NOW(),
    NOW()
  );

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION auth.create_user_profile() IS
  'Trigger function to automatically create a user profile when a new user is registered';

-- Create trigger on users table
CREATE TRIGGER trigger_create_user_profile
  AFTER INSERT ON auth.users
  FOR EACH ROW
  EXECUTE FUNCTION auth.create_user_profile();

COMMENT ON TRIGGER trigger_create_user_profile ON auth.users IS
  'Automatically creates a user profile entry when a new user is inserted';
