CREATE TABLE IF NOT EXISTS gateway_rate_limit_reservations (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  task_id uuid NOT NULL REFERENCES gateway_tasks(id) ON DELETE CASCADE,
  attempt_id uuid REFERENCES gateway_task_attempts(id) ON DELETE SET NULL,
  scope_type text NOT NULL,
  scope_key text NOT NULL,
  metric text NOT NULL,
  window_start timestamptz NOT NULL,
  limit_value numeric NOT NULL,
  reserved_amount numeric NOT NULL DEFAULT 0,
  actual_amount numeric NOT NULL DEFAULT 0,
  status text NOT NULL DEFAULT 'reserved',
  reason text,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now(),
  finalized_at timestamptz
);

CREATE INDEX IF NOT EXISTS idx_rate_limit_reservations_active
  ON gateway_rate_limit_reservations(status, scope_type, scope_key, metric, window_start);

CREATE INDEX IF NOT EXISTS idx_rate_limit_reservations_task
  ON gateway_rate_limit_reservations(task_id, attempt_id);
