-- =============================================
-- 租户-项目两级架构 - 回滚脚本
-- 执行顺序与正向脚本相反：业务表 → 默认数据 → 建表
-- =============================================

-- -----------------------------------------------
-- Step 1: 回滚业务表（删除 project_id 字段及索引）
-- -----------------------------------------------

ALTER TABLE iot_device DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_order DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_order_event DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_order_dispatch DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_order_queue DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_bus_area DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_area_device_relation DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_order_security_ext DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_area_security_user DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_order_clean_ext DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_cleaner_status DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_cleaner_performance_monthly DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_device_trajectory DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_inspection_record DROP INDEX idx_project_id, DROP COLUMN project_id;
ALTER TABLE ops_inspection_record_item DROP INDEX idx_project_id, DROP COLUMN project_id;

-- -----------------------------------------------
-- Step 2: 回滚默认数据（删除用户-项目关联 和 默认项目）
-- -----------------------------------------------

-- 删除系统自动生成的用户-项目关联
DELETE FROM system_user_project WHERE creator = 'system' AND deleted = 0;

-- 删除系统自动生成的默认项目
DELETE FROM system_project WHERE code = 'DEFAULT' AND creator = 'system' AND deleted = 0;

-- -----------------------------------------------
-- Step 3: 删除核心表
-- -----------------------------------------------

DROP TABLE IF EXISTS system_user_project;
DROP TABLE IF EXISTS system_project;

-- -----------------------------------------------
-- 验证
-- -----------------------------------------------
SELECT '回滚完成' AS status;
