-- 为 tb_package_usage 增加流量语义快照字段，并按当前套餐模板回填历史数据。

ALTER TABLE tb_package_usage
    ADD COLUMN virtual_total_mb_snapshot BIGINT NOT NULL DEFAULT 0,
    ADD COLUMN display_gain_ratio_snapshot DECIMAL(18,6) NOT NULL DEFAULT 1.0,
    ADD COLUMN enable_virtual_data_snapshot BOOLEAN NOT NULL DEFAULT FALSE;

COMMENT ON COLUMN tb_package_usage.virtual_total_mb_snapshot IS '虚总量快照（业务停机阈值）';
COMMENT ON COLUMN tb_package_usage.display_gain_ratio_snapshot IS '展示倍率快照（real_total_mb / virtual_total_mb）';
COMMENT ON COLUMN tb_package_usage.enable_virtual_data_snapshot IS '是否启用虚流量快照';

UPDATE tb_package_usage pu
SET
    virtual_total_mb_snapshot = CASE
        WHEN p.enable_virtual_data = TRUE AND p.virtual_data_mb > 0 THEN p.virtual_data_mb
        ELSE pu.data_limit_mb
    END,
    display_gain_ratio_snapshot = CASE
        WHEN p.enable_virtual_data = TRUE AND p.virtual_data_mb > 0 THEN ROUND((pu.data_limit_mb::NUMERIC / p.virtual_data_mb::NUMERIC), 6)
        ELSE 1.0
    END,
    enable_virtual_data_snapshot = CASE
        WHEN p.enable_virtual_data = TRUE AND p.virtual_data_mb > 0 THEN TRUE
        ELSE FALSE
    END
FROM tb_package p
WHERE p.id = pu.package_id;
