import { describe, expect, test } from "vitest";
import {
    activityTemplatePayloadFromForm,
    activityTemplateFormFromDto,
    createEmptyActivityTemplateForm,
    createNextActivityTask,
    giftFormValue,
} from "@/features/activity-templates/model.js";
import { activityTemplateFormSchema, validateActivityTemplateForPublish } from "@/features/activity-templates/schema";

describe("activity template form", () => {
    test("builds the owner-service snake_case aggregate without reward duration fields", () => {
        const form = createEmptyActivityTemplateForm("lalu");
        form.templateCode = "gift_challenge_2026";
        form.name = "Gift challenge July";
        form.allRegions = false;
        form.regionIds = ["1001", "1002"];
        form.timeRange = { startMs: 1_800_000_000_000, endMs: 1_800_086_400_000 };
        form.titleEn = "Gift Challenge";
        form.rulesEn = "Rule";
        form.gifts = [
            {
                coinPrice: "1999",
                giftId: "gift-1",
                iconUrl: "https://cdn.example.com/gift.webp",
                name: "Rose",
                priceVersion: "price-v2",
            },
        ];
        form.tasks = [
            {
                rewardResourceGroupId: "88",
                targetValue: "3",
                taskKey: "gift_count_3",
                taskType: "gift_count",
            },
        ];
        form.dailyRankRewards[0].resourceGroupId = "91";
        form.dailyRankRewards[1].resourceGroupId = "92";
        form.dailyRankRewards[2].resourceGroupId = "93";
        form.totalRankRewards.forEach((reward, index) => {
            reward.resourceGroupId = String(101 + index);
        });

        const parsed = activityTemplateFormSchema.parse(form);
        const payload = activityTemplatePayloadFromForm(parsed);

        expect(payload.template_code).toBe("gift_challenge_2026");
        expect(payload.region_ids).toEqual([1001, 1002]);
        expect(payload.gifts[0]).toMatchObject({
            coin_price: 1999,
            gift_id: "gift-1",
            price_version: "price-v2",
            sort_order: 1,
        });
        expect(payload.tasks[0]).toEqual({
            reward_resource_group_id: 88,
            sort_order: 1,
            target_value: 3,
            task_key: "gift_count_3",
            task_type: "gift_count",
        });
        expect(payload.tasks[0]).not.toHaveProperty("reward_valid_days");
        expect(payload.rank_rewards[0]).not.toHaveProperty("reward_valid_days");
        expect(payload).not.toHaveProperty("app_code");
        expect(payload).not.toHaveProperty("status");
        expect(payload).not.toHaveProperty("template_id");
    });

    test("rejects overlapping leaderboard ranges and invalid daily-visit targets", () => {
        const form = createEmptyActivityTemplateForm();
        form.templateCode = "gift_challenge";
        form.name = "Challenge";
        form.tasks[0].targetValue = "2";
        form.dailyRankRewards[1] = { ...form.dailyRankRewards[1], rankFrom: "1", rankTo: "2" };

        const result = activityTemplateFormSchema.safeParse(form);

        expect(result.success).toBe(false);
        expect(result.error.issues.map((issue) => issue.message)).toEqual(
            expect.arrayContaining(["每日进入活动任务的目标固定为 1", "奖励名次区间不能重叠"]),
        );
    });

    test("rejects duplicate daily-visit reward tasks", () => {
        const form = createEmptyActivityTemplateForm();
        form.templateCode = "gift_challenge";
        form.name = "Challenge";
        form.tasks.push({
            rewardResourceGroupId: "",
            targetValue: "1",
            taskKey: "daily_visit_bonus",
            taskType: "daily_visit",
        });

        const result = activityTemplateFormSchema.safeParse(form);

        expect(result.success).toBe(false);
        expect(result.error.issues.map((issue) => issue.message)).toContain("每日进入活动任务最多配置 1 个");
    });

    test("publish validation requires delivery, English content, gifts, tasks and rewards", () => {
        const form = createEmptyActivityTemplateForm();
        form.templateCode = "gift_challenge";
        form.name = "Challenge";
        const parsed = activityTemplateFormSchema.parse(form);

        const issues = validateActivityTemplateForPublish(parsed);

        expect(issues.map((issue) => issue.message)).toEqual(
            expect.arrayContaining([
                "发布前必须配置有效活动时间",
                "发布前必须选择投放区域",
                "发布前必须填写英语标题",
                "发布前至少配置 1 个礼物",
            ]),
        );
    });

    test("captures gift display snapshots from the selected gift", () => {
        expect(
            giftFormValue({
                coinPrice: 500,
                giftId: "g-1",
                name: "Star",
                priceVersion: "v9",
                resource: { previewUrl: "https://cdn.example.com/star.png" },
            }),
        ).toEqual({
            coinPrice: "500",
            giftId: "g-1",
            iconUrl: "https://cdn.example.com/star.png",
            name: "Star",
            priceVersion: "v9",
        });
    });

    test("preserves lifecycle and published-version metadata in editor form", () => {
        const form = activityTemplateFormFromDto({
            lifecycleStatus: "ongoing",
            publishedVersion: 7,
            status: "published",
        });

        expect(form.lifecycleStatus).toBe("ongoing");
        expect(form.publishedVersion).toBe(7);
    });

    test("allocates the first unused task key after rows are removed", () => {
        const task = createNextActivityTask(
            [{ taskKey: "gift_count_1" }, { taskKey: "gift_count_3" }, { taskKey: "daily_visit_1" }],
            "gift_count",
        );

        expect(task.taskKey).toBe("gift_count_2");
    });
});
