-- 为套餐使用记录增加购买时不可变计时条款快照；空值和零值保留为历史未快照标记。
ALTER TABLE tb_package_usage
    ADD COLUMN expiry_base_snapshot VARCHAR(30) NOT NULL DEFAULT '',
    ADD COLUMN calendar_type_snapshot VARCHAR(20) NOT NULL DEFAULT '',
    ADD COLUMN duration_months_snapshot INTEGER NOT NULL DEFAULT 0,
    ADD COLUMN duration_days_snapshot INTEGER NOT NULL DEFAULT 0;

COMMENT ON COLUMN tb_package_usage.expiry_base_snapshot IS '购买时生效条件快照，空字符串表示历史未快照';
COMMENT ON COLUMN tb_package_usage.calendar_type_snapshot IS '购买时周期类型快照，空字符串表示历史未快照';
COMMENT ON COLUMN tb_package_usage.duration_months_snapshot IS '购买时月数快照，0表示未使用或历史未快照';
COMMENT ON COLUMN tb_package_usage.duration_days_snapshot IS '购买时天数快照，0表示未使用或历史未快照';

-- 触发器只校验新记录及快照字段变更，历史空快照仍可更新状态等非快照字段。
CREATE OR REPLACE FUNCTION validate_package_usage_terms_snapshot()
RETURNS TRIGGER AS $$
BEGIN
    IF NEW.expiry_base_snapshot NOT IN ('from_purchase', 'from_activation')
        OR NOT (
            (NEW.calendar_type_snapshot = 'natural_month' AND NEW.duration_months_snapshot > 0 AND NEW.duration_days_snapshot = 0)
            OR (NEW.calendar_type_snapshot = 'by_day' AND NEW.duration_days_snapshot > 0 AND NEW.duration_months_snapshot = 0)
        ) THEN
        RAISE EXCEPTION '套餐使用记录计时快照不完整或无效';
    END IF;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER trg_validate_package_usage_terms_snapshot
BEFORE INSERT OR UPDATE OF expiry_base_snapshot, calendar_type_snapshot, duration_months_snapshot, duration_days_snapshot
ON tb_package_usage
FOR EACH ROW
EXECUTE FUNCTION validate_package_usage_terms_snapshot();
