import { describe, expect, test } from "vitest";
import {
    activeExperimentsByPool,
    buildExperimentCreateRequest,
    experimentDraft,
    experimentPoolFamilyKey,
    experimentStatusBadge,
    formatTrafficPercent,
    normalizeWhitelist,
    trafficPercentError,
    validateExperimentDraft,
} from "./experimentForm.js";

describe("ops center lucky gift ab experiment form", () => {
    test("requires a name and a 0-100 traffic percent", () => {
        expect(validateExperimentDraft(experimentDraft())).toEqual(["请填写实验名称"]);
        expect(validateExperimentDraft({ name: "rtp-98", trafficPercent: "5" })).toEqual([]);
        expect(validateExperimentDraft({ name: "  ", trafficPercent: "101" })).toEqual([
            "请填写实验名称",
            "实验组流量必须是 0-100 的百分比（0 表示仅白名单用户进入实验组）",
        ]);
        // 0 是合法灰度值：只有白名单用户进入实验组，不能按“必须大于 0”拦截。
        expect(validateExperimentDraft({ name: "rtp-98", trafficPercent: "0" })).toEqual([]);
        expect(trafficPercentError("")).not.toBe("");
        expect(trafficPercentError("-1")).not.toBe("");
        expect(trafficPercentError("abc")).not.toBe("");
        expect(trafficPercentError("100")).toBe("");
        expect(trafficPercentError(0)).toBe("");
    });

    test("normalizes whitelist entries by trimming and deduplicating", () => {
        expect(normalizeWhitelist([" 1001 ", "1001", "", "ext-9", null, "  "])).toEqual(["1001", "ext-9"]);
        expect(normalizeWhitelist(undefined)).toEqual([]);
    });

    test("builds a create request with treatment overrides and a runnable config", () => {
        const request = buildExperimentCreateRequest(
            { name: " 提高RTP ", trafficPercent: "12.5", whitelist: ["1001", " 1001", "ext-9"] },
            { app_code: "lalu", enabled: false, pool_id: "lucky" },
        );

        // 实验组配置必须直接可运行：enabled 强制 true，白名单全部作为 arm=treatment 的 override。
        expect(request).toEqual({
            config: { app_code: "lalu", enabled: true, pool_id: "lucky" },
            name: "提高RTP",
            overrides: [
                { arm: "treatment", user_key: "1001" },
                { arm: "treatment", user_key: "ext-9" },
            ],
            treatment_traffic_percent: 12.5,
        });
    });

    test("keeps only running and paused experiments as pool level publishing locks", () => {
        const running = {
            app_code: "lalu",
            experiment_id: "e2",
            pool_id: "lucky",
            started_at_ms: 200,
            status: "running",
            treatment_traffic_percent: 5,
        };
        const byPool = activeExperimentsByPool([
            { app_code: "lalu", experiment_id: "e1", pool_id: "lucky", started_at_ms: 100, status: "completed" },
            running,
            { app_code: "lalu", experiment_id: "e3", pool_id: "super_lucky", started_at_ms: 50, status: "paused" },
        ]);

        expect(byPool.get("lalu:lucky")).toBe(running);
        // paused 也算活跃：暂停只是流量临时回到对照组，实验仍独占该奖池的发布。
        expect(byPool.get("lalu:super_lucky")?.experiment_id).toBe("e3");
        // family key 不含 strategy_version：同一奖池的 fixed_v2/dynamic_v3 配置行共享同一实验封锁。
        expect(experimentPoolFamilyKey({ appCode: "LALU", poolId: "lucky", strategy_version: "fixed_v2" })).toBe(
            "lalu:lucky",
        );
        expect(experimentPoolFamilyKey({ app_code: "yumi" })).toBe("yumi:default");
    });

    test("maps experiment status to shared status badges with trimmed traffic percent", () => {
        expect(experimentStatusBadge({ status: "running", treatment_traffic_percent: 5 })).toEqual({
            label: "实验中 5%",
            tone: "warning",
        });
        expect(experimentStatusBadge({ status: "paused", treatment_traffic_percent: 5 })).toEqual({
            label: "实验暂停",
            tone: "warning",
        });
        expect(experimentStatusBadge({ status: "completed" })).toEqual({ label: "实验已结束", tone: "stopped" });
        expect(experimentStatusBadge(null)).toBeNull();
        expect(formatTrafficPercent(12.5)).toBe("12.5%");
        expect(formatTrafficPercent("7.00")).toBe("7%");
        expect(formatTrafficPercent("abc")).toBe("0%");
    });
});
