CREATE TABLE IF NOT EXISTS payment_finalize_checkpoints (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  purchase_id uuid NOT NULL,
  order_id uuid NOT NULL,
  provider_payment_id text NOT NULL,
  effect_key text NOT NULL,
  status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'running', 'completed')),
  attempt integer NOT NULL DEFAULT 0,
  lease_owner text,
  lease_expires_at timestamptz,
  updated_at timestamptz NOT NULL DEFAULT now(),
  completed_at timestamptz,
  CONSTRAINT payment_finalize_checkpoint_effect_uniq UNIQUE (purchase_id, effect_key)
);
CREATE INDEX IF NOT EXISTS payment_finalize_checkpoint_pending_idx
  ON payment_finalize_checkpoints (status, updated_at);
DROP INDEX IF EXISTS payment_finalize_checkpoint_provider_uniq;
CREATE UNIQUE INDEX IF NOT EXISTS payment_finalize_checkpoint_provider_uniq
  ON payment_finalize_checkpoints (provider_payment_id)
  WHERE effect_key = 'payment-claim';
