CREATE TABLE IF NOT EXISTS `bot_servers` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `server_id` VARCHAR(64) NOT NULL,
  `api_token` VARCHAR(128) NOT NULL,
  `instance_id` VARCHAR(80) NOT NULL DEFAULT '',
  `server_name` VARCHAR(120) NOT NULL DEFAULT '',
  `status` ENUM('active','inactive') NOT NULL DEFAULT 'active',
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_server_id` (`server_id`),
  UNIQUE KEY `uq_instance_id` (`instance_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `bot_server_orders` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `order_no` VARCHAR(64) NOT NULL,
  `source_chat_id` VARCHAR(40) NOT NULL,
  `source_server_id` VARCHAR(64) NOT NULL,
  `target_server_id` VARCHAR(64) NOT NULL,
  `payload_json` JSON NOT NULL,
  `api_result_json` JSON NULL,
  `sync_status` ENUM('new','fetched','synced') NOT NULL DEFAULT 'new',
  `fetched_at` DATETIME NULL,
  `synced_at` DATETIME NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_order_no` (`order_no`),
  KEY `idx_target_status` (`target_server_id`,`sync_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS `bot_voucher_check_requests` (
  `id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
  `request_no` VARCHAR(64) NOT NULL,
  `chat_id` VARCHAR(40) NOT NULL,
  `source_server_id` VARCHAR(64) NOT NULL,
  `bot_instance_id` VARCHAR(80) NOT NULL DEFAULT '',
  `card_number` VARCHAR(120) NOT NULL,
  `card_password` VARCHAR(120) NOT NULL,
  `request_status` ENUM('pending','submitted','completed','failed') NOT NULL DEFAULT 'pending',
  `result_json` JSON NULL,
  `api_result_json` JSON NULL,
  `created_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `updated_at` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_voucher_check_request_no` (`request_no`),
  KEY `idx_voucher_check_chat` (`chat_id`),
  KEY `idx_voucher_check_server` (`source_server_id`),
  KEY `idx_voucher_check_status` (`request_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
