
-- Add missing environment context columns to request_metadata
ALTER TABLE public.request_metadata
ADD COLUMN IF NOT EXISTS timezone TEXT,
ADD COLUMN IF NOT EXISTS referrer TEXT;

-- Add index for breadcrumbs lookup
CREATE INDEX IF NOT EXISTS idx_request_breadcrumbs_request_id 
ON public.request_breadcrumbs(request_id);

-- Update log_request_metadata function to accept and store new columns
CREATE OR REPLACE FUNCTION public.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,
  p_error_stack text DEFAULT NULL,
  p_breadcrumbs text DEFAULT '[]',
  p_environment_context text DEFAULT '{}',
  p_timezone text DEFAULT NULL,
  p_referrer text DEFAULT NULL
)
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
  v_breadcrumb jsonb;
  v_idx integer := 0;
BEGIN
  -- Insert main metadata record
  INSERT INTO request_metadata (
    request_id, user_id, endpoint, method, status_code, duration_ms,
    error_type, error_message, error_stack,
    user_agent, client_version, parent_request_id, trace_id,
    timezone, referrer
  ) VALUES (
    p_request_id, p_user_id, p_endpoint, p_method, p_status_code, p_duration_ms,
    p_error_type, p_error_message, p_error_stack,
    p_user_agent, p_client_version, p_parent_request_id, p_trace_id,
    p_timezone, p_referrer
  );
  
  -- Parse and insert breadcrumbs into relational table
  IF p_breadcrumbs IS NOT NULL AND p_breadcrumbs != '[]' THEN
    BEGIN
      FOR v_breadcrumb IN SELECT * FROM jsonb_array_elements(p_breadcrumbs::jsonb)
      LOOP
        INSERT INTO request_breadcrumbs (
          request_id, timestamp, category, message, level, sequence_order
        ) VALUES (
          p_request_id,
          COALESCE((v_breadcrumb->>'timestamp')::timestamptz, NOW()),
          COALESCE(v_breadcrumb->>'category', 'unknown'),
          COALESCE(v_breadcrumb->>'message', ''),
          COALESCE(v_breadcrumb->>'level', 'info')::text,
          v_idx
        );
        v_idx := v_idx + 1;
      END LOOP;
    EXCEPTION WHEN OTHERS THEN
      RAISE NOTICE 'Failed to parse breadcrumbs: %', SQLERRM;
    END;
  END IF;
END;
$function$;
