-- Create RPC function for logging request metadata
-- This allows us to insert into request_metadata before types regenerate

CREATE OR REPLACE FUNCTION log_request_metadata(
  p_request_id uuid,
  p_user_id uuid DEFAULT NULL,
  p_endpoint text DEFAULT NULL,
  p_method text DEFAULT NULL,
  p_status_code integer DEFAULT NULL,
  p_duration_ms integer DEFAULT NULL,
  p_error_type text DEFAULT NULL,
  p_error_message text DEFAULT NULL,
  p_user_agent text DEFAULT NULL,
  p_client_version text DEFAULT NULL,
  p_parent_request_id uuid DEFAULT NULL,
  p_trace_id uuid DEFAULT NULL
)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  INSERT INTO request_metadata (
    request_id,
    user_id,
    endpoint,
    method,
    status_code,
    duration_ms,
    error_type,
    error_message,
    user_agent,
    client_version,
    parent_request_id,
    trace_id
  ) VALUES (
    p_request_id,
    p_user_id,
    p_endpoint,
    p_method,
    p_status_code,
    p_duration_ms,
    p_error_type,
    p_error_message,
    p_user_agent,
    p_client_version,
    p_parent_request_id,
    p_trace_id
  );
END;
$$;

COMMENT ON FUNCTION log_request_metadata IS 'Logs request metadata for monitoring and debugging';

-- Grant execute permission to authenticated users
GRANT EXECUTE ON FUNCTION log_request_metadata TO authenticated;
GRANT EXECUTE ON FUNCTION log_request_metadata TO anon;