-- 数据回填脚本：为历史订单填充 purchase_role 和 operator_type
-- 用途：将现有平台代购订单标记为 purchased_by_platform
-- 执行时间：预计 < 1 秒（取决于历史订单数量）
-- 回滚方法：将 purchase_role 和 operator_type 设为 NULL

BEGIN;

-- 1. 回填平台代购订单（offline + is_purchase_on_behalf = true）
UPDATE tb_order
SET
    purchase_role = 'purchased_by_platform',
    operator_type = 'platform'
WHERE
    payment_method = 'offline'
    AND is_purchase_on_behalf = true
    AND purchase_role IS NULL;

-- 2. 显示回填统计信息
DO $$
DECLARE
    updated_count INTEGER;
BEGIN
    SELECT COUNT(*) INTO updated_count
    FROM tb_order
    WHERE purchase_role = 'purchased_by_platform'
      AND operator_type = 'platform';

    RAISE NOTICE '已回填 % 条平台代购订单', updated_count;
END $$;

COMMIT;

-- 验证回填结果
SELECT
    purchase_role,
    operator_type,
    payment_method,
    is_purchase_on_behalf,
    COUNT(*) as count
FROM tb_order
WHERE purchase_role IS NOT NULL
GROUP BY purchase_role, operator_type, payment_method, is_purchase_on_behalf
ORDER BY count DESC;
