ALTER TABLE qipai_stores
  ADD COLUMN cancellation_cutoff_minutes INT UNSIGNED NOT NULL DEFAULT 120
    AFTER notification_url,
  ADD COLUMN cancellation_fee_bps SMALLINT UNSIGNED NOT NULL DEFAULT 0
    AFTER cancellation_cutoff_minutes;

ALTER TABLE qipai_orders
  ADD COLUMN adjustment_amount_cents INT NOT NULL DEFAULT 0 AFTER paid_amount_cents,
  ADD COLUMN operator_note VARCHAR(512) NOT NULL DEFAULT '' AFTER adjustment_amount_cents;

CREATE TABLE IF NOT EXISTS qipai_order_adjustments (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tenant_id BIGINT UNSIGNED NOT NULL,
  order_id BIGINT UNSIGNED NOT NULL,
  adjustment_type VARCHAR(32) NOT NULL,
  actor_id BIGINT UNSIGNED NOT NULL,
  source VARCHAR(32) NOT NULL,
  trace_id VARCHAR(128) NOT NULL,
  reason VARCHAR(512) NOT NULL DEFAULT '',
  before_values JSON NOT NULL,
  after_values JSON NOT NULL,
  amount_delta_cents INT NOT NULL DEFAULT 0,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  CONSTRAINT fk_qipai_order_adjustment_tenant
    FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id),
  CONSTRAINT fk_qipai_order_adjustment_order
    FOREIGN KEY (order_id) REFERENCES qipai_orders(id),
  CONSTRAINT fk_qipai_order_adjustment_actor
    FOREIGN KEY (actor_id) REFERENCES qipai_users(id),
  UNIQUE KEY uq_qipai_order_adjustment_trace (tenant_id, order_id, trace_id),
  KEY idx_qipai_order_adjustment_order (tenant_id, order_id, id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO qipai_schema_migrations (version, name)
VALUES ('2026062013', 'm04c_order_adjustments');
