CREATE TABLE IF NOT EXISTS cart_checkout_captures (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(), checkout_key text NOT NULL, order_id uuid NOT NULL,
  order_line_id uuid NOT NULL, provider_payment_id text, provider_hold_id text NOT NULL, amount_agorot integer NOT NULL,
  checkout_order_ids uuid[] NOT NULL, status text NOT NULL DEFAULT 'pending', capture_idempotency_key text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT cart_checkout_captures_checkout_order_uniq UNIQUE (checkout_key, order_id),
  CONSTRAINT cart_checkout_captures_payment_uniq UNIQUE (provider_payment_id)
  ,CONSTRAINT cart_checkout_captures_hold_uniq UNIQUE (provider_hold_id)
);
CREATE TABLE IF NOT EXISTS cart_checkout_compensations (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(), checkout_key text NOT NULL, order_id uuid NOT NULL,
  order_line_id uuid NOT NULL, provider_payment_id text NOT NULL, amount_agorot integer NOT NULL,
  checkout_order_ids uuid[] NOT NULL,
  refund_idempotency_key text NOT NULL, status text NOT NULL DEFAULT 'pending', provider_refund_id text,
  last_error text, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),
  CONSTRAINT cart_checkout_compensations_status_ck CHECK (status IN ('pending','processing','refunded','cleaning','cleanup_completed','failed')),
  CONSTRAINT cart_checkout_compensations_payment_uniq UNIQUE (provider_payment_id),
  CONSTRAINT cart_checkout_compensations_checkout_order_uniq UNIQUE (checkout_key, order_id)
);
CREATE INDEX IF NOT EXISTS cart_checkout_compensations_status_idx ON cart_checkout_compensations (status, updated_at);
CREATE INDEX IF NOT EXISTS cart_checkout_captures_status_idx ON cart_checkout_captures (status, created_at);
