import { describe, expect, test } from "vitest";
import { normalizeVipBenefitMetadata, updateVipBenefitMetadataField, vipBenefitMetadataField } from "./metadata.js";

describe("VIP benefit metadata", () => {
    test("updates structured fields without dropping unrelated metadata", () => {
        const rebate = updateVipBenefitMetadataField('{"channel":"vip","coin_amount":20}', "coin_amount", 88);
        const notice = updateVipBenefitMetadataField('{"theme":"gold","message":"旧文案"}', "message", "欢迎上线");

        expect(JSON.parse(rebate)).toEqual({ channel: "vip", coin_amount: 88 });
        expect(JSON.parse(notice)).toEqual({ theme: "gold", message: "欢迎上线" });
        expect(vipBenefitMetadataField(rebate, "coin_amount")).toBe("88");
    });

    test("requires a positive coin amount only when the rebate benefit is active", () => {
        expect(() =>
            normalizeVipBenefitMetadata({
                benefitCode: "daily_coin_rebate",
                label: "VIP6 的金币返现",
                metadataJson: '{"source":"daily"}',
                status: "active",
            }),
        ).toThrow("启用时每日返现金币必须为正整数");

        expect(
            JSON.parse(
                normalizeVipBenefitMetadata({
                    benefitCode: "daily_coin_rebate",
                    label: "VIP6 的金币返现",
                    metadataJson: '{"source":"daily"}',
                    status: "disabled",
                }),
            ),
        ).toEqual({ source: "daily" });
    });

    test("normalizes coin amount and limits the online notice message", () => {
        expect(
            JSON.parse(
                normalizeVipBenefitMetadata({
                    benefitCode: "daily_coin_rebate",
                    label: "VIP6 的金币返现",
                    metadataJson: '{"source":"daily","coin_amount":"120"}',
                    status: "active",
                }),
            ),
        ).toEqual({ source: "daily", coin_amount: 120 });

        expect(() =>
            normalizeVipBenefitMetadata({
                benefitCode: "online_global_notice",
                label: "VIP9 的上线全服通知",
                metadataJson: JSON.stringify({ message: "欢".repeat(257), theme: "gold" }),
                status: "active",
            }),
        ).toThrow("上线飘屏文案不能超过 256 个字符");
    });
});
