-- 1. Create ops_area_device_relation table
CREATE TABLE `ops_area_device_relation` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '主键',
  `area_id` BIGINT NOT NULL COMMENT '运营区域ID',
  `device_id` BIGINT NOT NULL COMMENT 'IoT设备ID',
  `device_key` VARCHAR(100) NOT NULL COMMENT '设备Key(冗余)',
  `product_id` BIGINT NOT NULL COMMENT '产品ID',
  `product_key` VARCHAR(100) NOT NULL COMMENT '产品Key(冗余)',
  `relation_type` VARCHAR(50) NOT NULL COMMENT '关联类型:TRAFFIC_COUNTER/BEACON/BADGE',
  `config_data` TEXT COMMENT '配置数据(JSON格式)',
  `enabled` TINYINT(1) NOT NULL DEFAULT 1 COMMENT '是否启用',
  `creator` VARCHAR(64) DEFAULT '' COMMENT '创建者',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `updater` VARCHAR(64) DEFAULT '' COMMENT '更新者',
  `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` BIT(1) NOT NULL DEFAULT b'0' COMMENT '是否删除',
  `tenant_id` BIGINT NOT NULL DEFAULT 0 COMMENT '租户ID',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_device` (`device_id`, `deleted`),
  KEY `idx_area_id` (`area_id`),
  KEY `idx_product_key` (`product_key`),
  KEY `idx_relation_type` (`relation_type`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='运营区域设备关联表';

-- 2. Alter ops_order table to add trigger fields
ALTER TABLE `ops_order` 
ADD COLUMN `trigger_source` VARCHAR(50) DEFAULT 'MANUAL' COMMENT '触发来源：MANUAL/IOT_TRAFFIC/IOT_ALERT' AFTER `source_type`,
ADD COLUMN `trigger_rule_id` BIGINT DEFAULT NULL COMMENT '触发规则ID(关联iot_scene_rule.id)' AFTER `trigger_source`,
ADD COLUMN `trigger_device_id` BIGINT DEFAULT NULL COMMENT '触发设备ID' AFTER `trigger_rule_id`,
ADD COLUMN `trigger_device_key` VARCHAR(100) DEFAULT NULL COMMENT '触发设备Key' AFTER `trigger_device_id`,
ADD COLUMN `assignee_device_id` BIGINT DEFAULT NULL COMMENT '负责设备ID(关联iot_device.id)' AFTER `assignee_id`,
ADD COLUMN `assignee_device_key` VARCHAR(100) DEFAULT NULL COMMENT '负责设备Key' AFTER `assignee_device_id`;
