-- ============================================================================
-- OrbiQuant IA - Trading Platform
-- Schema: auth
-- File: functions/02-log_auth_event.sql
-- Description: Function to log authentication events to auth_logs table
-- ============================================================================

CREATE OR REPLACE FUNCTION auth.log_auth_event(
  p_event_type auth.auth_event_type,
  p_user_id UUID DEFAULT NULL,
  p_email CITEXT DEFAULT NULL,
  p_ip_address INET DEFAULT NULL,
  p_user_agent TEXT DEFAULT NULL,
  p_session_id UUID DEFAULT NULL,
  p_success BOOLEAN DEFAULT true,
  p_failure_reason VARCHAR(255) DEFAULT NULL,
  p_metadata JSONB DEFAULT '{}'::jsonb
)
RETURNS UUID AS $$
DECLARE
  v_log_id UUID;
BEGIN
  INSERT INTO auth.auth_logs (
    event_type,
    user_id,
    email,
    ip_address,
    user_agent,
    session_id,
    success,
    failure_reason,
    metadata,
    created_at
  ) VALUES (
    p_event_type,
    p_user_id,
    p_email,
    p_ip_address,
    p_user_agent,
    p_session_id,
    p_success,
    p_failure_reason,
    p_metadata,
    NOW()
  )
  RETURNING id INTO v_log_id;

  RETURN v_log_id;
END;
$$ LANGUAGE plpgsql;

COMMENT ON FUNCTION auth.log_auth_event(
  auth.auth_event_type,
  UUID,
  CITEXT,
  INET,
  TEXT,
  UUID,
  BOOLEAN,
  VARCHAR,
  JSONB
) IS 'Logs authentication events to the auth_logs table with optional metadata';

-- Example usage:
-- SELECT auth.log_auth_event(
--   'login'::auth.auth_event_type,
--   '123e4567-e89b-12d3-a456-426614174000'::UUID,
--   'user@example.com'::CITEXT,
--   '192.168.1.1'::INET,
--   'Mozilla/5.0...',
--   '123e4567-e89b-12d3-a456-426614174001'::UUID,
--   true,
--   NULL,
--   '{"device": "mobile"}'::JSONB
-- );
