-- 支付退款字段补齐：兼容已经应用过 000001 的现有数据库。

SET @has_refund_status := (
  SELECT COUNT(*) FROM information_schema.columns
  WHERE table_schema = DATABASE() AND table_name = 'rental_orders' AND column_name = 'refund_status'
);
SET @sql := IF(@has_refund_status = 0,
  'ALTER TABLE rental_orders ADD COLUMN refund_status VARCHAR(32) NOT NULL DEFAULT ''none'' AFTER settlement_status',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @has_refund_amount_cent := (
  SELECT COUNT(*) FROM information_schema.columns
  WHERE table_schema = DATABASE() AND table_name = 'rental_orders' AND column_name = 'refund_amount_cent'
);
SET @sql := IF(@has_refund_amount_cent = 0,
  'ALTER TABLE rental_orders ADD COLUMN refund_amount_cent BIGINT NOT NULL DEFAULT 0 AFTER refund_status',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @has_refunded_at := (
  SELECT COUNT(*) FROM information_schema.columns
  WHERE table_schema = DATABASE() AND table_name = 'rental_orders' AND column_name = 'refunded_at'
);
SET @sql := IF(@has_refunded_at = 0,
  'ALTER TABLE rental_orders ADD COLUMN refunded_at DATETIME NULL AFTER refund_amount_cent',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @has_order_refund_idx := (
  SELECT COUNT(*) FROM information_schema.statistics
  WHERE table_schema = DATABASE() AND table_name = 'rental_orders' AND index_name = 'idx_rental_orders_refund_status'
);
SET @sql := IF(@has_order_refund_idx = 0,
  'ALTER TABLE rental_orders ADD KEY idx_rental_orders_refund_status (refund_status)',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @has_payment_biz_type := (
  SELECT COUNT(*) FROM information_schema.columns
  WHERE table_schema = DATABASE() AND table_name = 'payment_orders' AND column_name = 'biz_type'
);
SET @sql := IF(@has_payment_biz_type = 0,
  'ALTER TABLE payment_orders ADD COLUMN biz_type VARCHAR(32) NOT NULL DEFAULT ''order_pay'' AFTER amount_cent',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @has_payment_biz_idx := (
  SELECT COUNT(*) FROM information_schema.statistics
  WHERE table_schema = DATABASE() AND table_name = 'payment_orders' AND index_name = 'idx_payment_orders_biz_type'
);
SET @sql := IF(@has_payment_biz_idx = 0,
  'ALTER TABLE payment_orders ADD KEY idx_payment_orders_biz_type (biz_type)',
  'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

UPDATE payment_orders
SET biz_type = CASE WHEN order_id = 0 THEN 'wallet_recharge' ELSE 'order_pay' END
WHERE biz_type = '' OR biz_type = 'order_pay';
