ALTER TABLE qipai_refunds
  ADD COLUMN client_request_id VARCHAR(128) NOT NULL AFTER order_id,
  ADD COLUMN provider VARCHAR(32) NOT NULL DEFAULT 'WECHAT' AFTER client_request_id,
  ADD COLUMN provider_callback_id VARCHAR(128) NULL AFTER provider_refund_id,
  ADD COLUMN failure_code VARCHAR(64) NOT NULL DEFAULT '' AFTER completed_at,
  ADD COLUMN raw_response JSON NULL AFTER failure_code,
  ADD UNIQUE KEY uq_qipai_refund_client_request (tenant_id, client_request_id),
  ADD UNIQUE KEY uq_qipai_refund_callback
    (tenant_id, provider, provider_callback_id);

CREATE TABLE IF NOT EXISTS qipai_reconciliation_runs (
  id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tenant_id BIGINT UNSIGNED NOT NULL,
  payment_config_id BIGINT UNSIGNED NOT NULL,
  bill_date DATE NOT NULL,
  bill_type VARCHAR(16) NOT NULL,
  status VARCHAR(32) NOT NULL DEFAULT 'REQUESTED',
  download_url VARCHAR(2048) NOT NULL DEFAULT '',
  error_code VARCHAR(64) NOT NULL DEFAULT '',
  requested_by BIGINT UNSIGNED NULL,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  completed_at DATETIME(3) NULL,
  CONSTRAINT fk_qipai_reconciliation_tenant
    FOREIGN KEY (tenant_id) REFERENCES qipai_tenants(id),
  CONSTRAINT fk_qipai_reconciliation_config
    FOREIGN KEY (payment_config_id) REFERENCES qipai_payment_configs(id),
  UNIQUE KEY uq_qipai_reconciliation_request
    (tenant_id, payment_config_id, bill_date, bill_type),
  KEY idx_qipai_reconciliation_status (tenant_id, status, bill_date)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT IGNORE INTO qipai_schema_migrations (version, name)
VALUES ('2026062216', 'm05b_wechat_refunds');
