-- Request Metadata Table
-- Stores detailed context about API requests for monitoring and debugging

CREATE TABLE IF NOT EXISTS request_metadata (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  request_id uuid UNIQUE NOT NULL,
  user_id uuid REFERENCES auth.users(id) ON DELETE SET NULL,
  
  -- Request context
  endpoint text NOT NULL,
  method text NOT NULL,
  status_code integer,
  
  -- Timing
  started_at timestamptz NOT NULL DEFAULT now(),
  completed_at timestamptz,
  duration_ms integer,
  
  -- Client info
  user_agent text,
  client_version text,
  ip_address_hash text,
  
  -- Error tracking
  error_type text,
  error_message text,
  retry_count integer DEFAULT 0,
  
  -- Correlation for distributed tracing
  parent_request_id uuid,
  trace_id uuid,
  
  created_at timestamptz NOT NULL DEFAULT now()
);

-- Indexes for efficient querying
CREATE INDEX IF NOT EXISTS idx_request_metadata_user_id ON request_metadata(user_id);
CREATE INDEX IF NOT EXISTS idx_request_metadata_started_at ON request_metadata(started_at DESC);
CREATE INDEX IF NOT EXISTS idx_request_metadata_trace_id ON request_metadata(trace_id);
CREATE INDEX IF NOT EXISTS idx_request_metadata_request_id ON request_metadata(request_id);
CREATE INDEX IF NOT EXISTS idx_request_metadata_status_code ON request_metadata(status_code);

-- Enable RLS
ALTER TABLE request_metadata ENABLE ROW LEVEL SECURITY;

-- Policies: Only admins and system can read/write
CREATE POLICY "Service role can insert request metadata"
  ON request_metadata
  FOR INSERT
  WITH CHECK (true);

CREATE POLICY "Service role can read request metadata"
  ON request_metadata
  FOR SELECT
  USING (true);

-- Function to clean up old request metadata (keep 30 days)
CREATE OR REPLACE FUNCTION cleanup_old_request_metadata()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
BEGIN
  DELETE FROM request_metadata
  WHERE created_at < now() - interval '30 days';
END;
$$;

COMMENT ON TABLE request_metadata IS 'Stores request correlation IDs and metadata for monitoring and debugging';
COMMENT ON COLUMN request_metadata.request_id IS 'Unique correlation ID for this request';
COMMENT ON COLUMN request_metadata.trace_id IS 'Distributed tracing ID for tracking related requests';
COMMENT ON COLUMN request_metadata.parent_request_id IS 'Parent request ID for chained operations';