-- 清理演示过程数据：秒杀活动、秒杀订单、admin 前台订单/拼团/评价/收藏/通知数据
-- 适用于已导入 flash_sale_db.sql 的 MySQL 数据库。

SET @admin_user_id := (SELECT id
                       FROM users
                       WHERE username = 'admin'
                       LIMIT 1);

CREATE TEMPORARY TABLE IF NOT EXISTS cleanup_group_ids
(
    id BIGINT PRIMARY KEY
) ENGINE = Memory;

CREATE TEMPORARY TABLE IF NOT EXISTS cleanup_order_ids
(
    id BIGINT PRIMARY KEY
) ENGINE = Memory;

TRUNCATE TABLE cleanup_group_ids;
TRUNCATE TABLE cleanup_order_ids;

INSERT IGNORE INTO cleanup_group_ids (id)
SELECT id
FROM group_buying_group
WHERE leader_user_id = @admin_user_id;

INSERT IGNORE INTO cleanup_order_ids (id)
SELECT id
FROM orders
WHERE order_type = 2
   OR flash_sale_id IS NOT NULL
   OR user_id = @admin_user_id
   OR group_buying_group_id IN (SELECT id FROM cleanup_group_ids);

DELETE n
FROM notifications n
WHERE n.user_id = @admin_user_id
   OR n.link IN (SELECT CONCAT('/order/', id)
                 FROM cleanup_order_ids);

DELETE pr
FROM product_reviews pr
WHERE pr.user_id = @admin_user_id
   OR pr.order_id IN (SELECT id FROM cleanup_order_ids);

DELETE r
FROM order_returns r
WHERE r.user_id = @admin_user_id
   OR r.order_id IN (SELECT id FROM cleanup_order_ids);

DELETE oi
FROM order_items oi
WHERE oi.order_id IN (SELECT id FROM cleanup_order_ids);

DELETE gbm
FROM group_buying_member gbm
WHERE gbm.user_id = @admin_user_id
   OR gbm.order_id IN (SELECT id FROM cleanup_order_ids)
   OR gbm.group_id IN (SELECT id FROM cleanup_group_ids);

DELETE o
FROM orders o
WHERE o.id IN (SELECT id FROM cleanup_order_ids);

DELETE g
FROM group_buying_group g
WHERE g.id IN (SELECT id FROM cleanup_group_ids);

DELETE uf
FROM user_favorites uf
WHERE uf.user_id = @admin_user_id;

DELETE ua
FROM user_addresses ua
WHERE ua.user_id = @admin_user_id;

DELETE
FROM flash_sales;

UPDATE users
SET role = 'ADMIN'
WHERE username = 'admin';

DROP TEMPORARY TABLE IF EXISTS cleanup_order_ids;
DROP TEMPORARY TABLE IF EXISTS cleanup_group_ids;
