SET @table_schema = DATABASE();

SET @ddl = IF(
    EXISTS(
        SELECT 1
        FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = @table_schema
          AND TABLE_NAME = 'order_user_purchase_pay'
          AND COLUMN_NAME = 'receipt_type'
    ),
    'SELECT 1',
    "ALTER TABLE `order_user_purchase_pay` ADD COLUMN `receipt_type` varchar(32) NOT NULL DEFAULT 'PAYMENT' COMMENT '单据类型 PAYMENT/RECEIPT' AFTER `reference_id`"
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
    EXISTS(
        SELECT 1
        FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = @table_schema
          AND TABLE_NAME = 'order_user_purchase_pay'
          AND COLUMN_NAME = 'product_descriptor'
    ),
    'SELECT 1',
    "ALTER TABLE `order_user_purchase_pay` ADD COLUMN `product_descriptor` varchar(255) NOT NULL DEFAULT '' COMMENT '商品描述' AFTER `product_content`"
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @ddl = IF(
    EXISTS(
        SELECT 1
        FROM information_schema.COLUMNS
        WHERE TABLE_SCHEMA = @table_schema
          AND TABLE_NAME = 'order_user_purchase_pay'
          AND COLUMN_NAME = 'reason'
    ),
    'SELECT 1',
    "ALTER TABLE `order_user_purchase_pay` ADD COLUMN `reason` varchar(255) NOT NULL DEFAULT '' COMMENT '失败或挂起原因' AFTER `pay_status`"
);
PREPARE stmt FROM @ddl;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

UPDATE `order_user_purchase_pay`
SET `receipt_type` = 'PAYMENT'
WHERE `receipt_type` = '';

CREATE TABLE IF NOT EXISTS `order_user_purchase_pay_notice` (
  `id` bigint NOT NULL COMMENT '主键ID',
  `purchase_pay_id` bigint NOT NULL COMMENT '支付预订单ID',
  `event_id` varchar(128) NOT NULL DEFAULT '' COMMENT '事件标识',
  `notice_type` varchar(64) NOT NULL DEFAULT '' COMMENT '通知类型',
  `notice_data` longtext COMMENT '通知内容(JSON)',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `create_user` bigint DEFAULT NULL COMMENT '创建人',
  `update_user` bigint DEFAULT NULL COMMENT '更新人',
  PRIMARY KEY (`id`),
  KEY `idx_purchase_pay_notice_order` (`purchase_pay_id`, `id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Web支付通知明细';
