import { describe, expect, test } from "vitest";
import { FormValidationError, parseForm } from "@/shared/forms/validation";
import {
    emojiPackFormSchema,
    giftFormSchema,
    resourceFormSchema,
    resourceGrantFormSchema,
    resourceGroupCreateFormSchema,
    resourceIdentityAutoGrantFormSchema,
    resourceShopItemsFormSchema,
} from "./schema.js";

describe("resource form schema", () => {
    test("allows profile card resources", () => {
        const payload = parseForm(resourceFormSchema, {
            animationUrl: "https://media.haiyihy.com/resource/profile-card.pag",
            badgeForm: "tile",
            enabled: true,
            managerGrantEnabled: true,
            metadataJson:
                '{"profile_card_layout":{"source_width":1136,"source_height":1680,"color_content_width":750,"content_top":117,"content_bottom":1666,"content_height":1550,"content_top_ratio":0.069643,"content_height_ratio":0.922619,"detect_version":1}}',
            name: "Profile Card",
            previewUrl: "https://media.haiyihy.com/resource/profile-card-cover.png",
            priceType: "free",
            resourceCode: "profile_card_gold",
            resourceType: "profile_card",
            walletAssetAmount: "",
        });

        expect(payload.resourceType).toBe("profile_card");
        expect(payload.metadataJson).toContain("profile_card_layout");
    });

    test("requires badge form for badge resources", () => {
        const payload = parseForm(resourceFormSchema, {
            animationUrl: "https://media.haiyihy.com/resource/badge.pag",
            badgeForm: "strip",
            badgeKind: "level",
            enabled: true,
            levelTrack: "wealth",
            managerGrantEnabled: true,
            name: "VIP Badge",
            previewUrl: "https://media.haiyihy.com/resource/badge.png",
            priceType: "free",
            resourceCode: "badge_vip",
            resourceType: "badge",
            walletAssetAmount: "",
        });

        expect(payload.badgeForm).toBe("strip");
        expect(payload.badgeKind).toBe("level");
        expect(payload.levelTrack).toBe("wealth");
        expect(() =>
            parseForm(resourceFormSchema, {
                animationUrl: "https://media.haiyihy.com/resource/badge.pag",
                enabled: true,
                managerGrantEnabled: true,
                name: "VIP Badge",
                previewUrl: "https://media.haiyihy.com/resource/badge.png",
                priceType: "free",
                resourceCode: "badge_vip",
                resourceType: "badge",
                walletAssetAmount: "",
            }),
        ).toThrow(FormValidationError);
        expect(() =>
            parseForm(resourceFormSchema, {
                animationUrl: "https://media.haiyihy.com/resource/badge.pag",
                badgeForm: "strip",
                badgeKind: "level",
                enabled: true,
                managerGrantEnabled: true,
                name: "VIP Badge",
                previewUrl: "https://media.haiyihy.com/resource/badge.png",
                priceType: "free",
                resourceCode: "badge_vip_level",
                resourceType: "badge",
                walletAssetAmount: "",
            }),
        ).toThrow(FormValidationError);
    });

    test("requires level track for level avatar frame resources", () => {
        const payload = parseForm(resourceFormSchema, {
            animationUrl: "https://media.haiyihy.com/resource/frame.pag",
            avatarFrameKind: "level",
            enabled: true,
            levelTrack: "game",
            managerGrantEnabled: true,
            name: "Game Level Frame",
            previewUrl: "https://media.haiyihy.com/resource/frame.png",
            priceType: "free",
            resourceCode: "game_level_frame",
            resourceType: "avatar_frame",
            walletAssetAmount: "",
        });

        expect(payload.avatarFrameKind).toBe("level");
        expect(payload.levelTrack).toBe("game");
        expect(() =>
            parseForm(resourceFormSchema, {
                animationUrl: "https://media.haiyihy.com/resource/frame.pag",
                avatarFrameKind: "level",
                enabled: true,
                managerGrantEnabled: true,
                name: "Game Level Frame",
                previewUrl: "https://media.haiyihy.com/resource/frame.png",
                priceType: "free",
                resourceCode: "game_level_frame",
                resourceType: "avatar_frame",
                walletAssetAmount: "",
            }),
        ).toThrow(FormValidationError);
    });

    test("requires explicit confirmation before saving mp4 alpha layout", () => {
        const basePayload = {
            animationUrl: "https://media.haiyihy.com/resource/gift.mp4",
            enabled: true,
            managerGrantEnabled: true,
            name: "Gift",
            previewUrl: "https://media.haiyihy.com/resource/gift.png",
            coinPrice: "1",
            priceType: "coin",
            resourceCode: "gift_love",
            resourceType: "gift",
            walletAssetAmount: "",
        };
        const layout = {
            alpha_frame: [0, 0, 750, 1334],
            alpha_layout: "alpha_left_rgb_right",
            detect_version: 1,
            rgb_frame: [750, 0, 750, 1334],
            video_h: 1334,
            video_w: 1500,
        };

        expect(() =>
            parseForm(resourceFormSchema, {
                ...basePayload,
                metadataJson: JSON.stringify({
                    animation_format: "mp4",
                    mp4_alpha_layout: { ...layout, confirmed: false },
                }),
            }),
        ).toThrow(FormValidationError);

        const payload = parseForm(resourceFormSchema, {
            ...basePayload,
            metadataJson: JSON.stringify({ animation_format: "mp4", mp4_alpha_layout: { ...layout, confirmed: true } }),
        });
        expect(payload.metadataJson).toContain("mp4_alpha_layout");
    });

    test("allows resource group resource items without wallet asset type", () => {
        const payload = parseForm(resourceGroupCreateFormSchema, {
            description: "",
            enabled: true,
            groupCode: "starter_pack",
            items: [
                {
                    durationDays: "7",
                    itemType: "resource",
                    resourceId: "11",
                    sortOrder: "0",
                    walletAssetAmount: "",
                    walletAssetType: "",
                },
            ],
            name: "Starter Pack",
            sortOrder: "0",
        });

        expect(payload.items[0].walletAssetType).toBeUndefined();
    });

    test("rejects invalid wallet asset type with Chinese message", () => {
        expect(() =>
            parseForm(resourceGroupCreateFormSchema, {
                description: "",
                enabled: true,
                groupCode: "starter_pack",
                items: [
                    {
                        durationDays: "",
                        itemType: "wallet_asset",
                        resourceId: "",
                        sortOrder: "0",
                        walletAssetAmount: "100",
                        walletAssetType: "gold",
                    },
                ],
                name: "Starter Pack",
                sortOrder: "0",
            }),
        ).toThrow(FormValidationError);
    });

    test("validates identity auto grant resource group config", () => {
        const payload = parseForm(resourceIdentityAutoGrantFormSchema, {
            items: [
                { identityType: "host", resourceGroupId: "11" },
                { identityType: "bd", resourceGroupId: "12" },
                { identityType: "bd_leader", resourceGroupId: "13" },
                { identityType: "agency", resourceGroupId: "14" },
                { identityType: "manager", resourceGroupId: "" },
            ],
        });

        expect(payload.items).toHaveLength(5);
        expect(payload.items[4].resourceGroupId).toBe("");
    });

    test("rejects incomplete identity auto grant config", () => {
        expect(() =>
            parseForm(resourceIdentityAutoGrantFormSchema, {
                items: [
                    { identityType: "host", resourceGroupId: "11" },
                    { identityType: "bd", resourceGroupId: "12" },
                    { identityType: "bd_leader", resourceGroupId: "13" },
                    { identityType: "agency", resourceGroupId: "14" },
                ],
            }),
        ).toThrow(FormValidationError);
    });

    test("rejects duplicate identity auto grant config", () => {
        expect(() =>
            parseForm(resourceIdentityAutoGrantFormSchema, {
                items: [
                    { identityType: "host", resourceGroupId: "11" },
                    { identityType: "bd", resourceGroupId: "12" },
                    { identityType: "bd_leader", resourceGroupId: "13" },
                    { identityType: "agency", resourceGroupId: "14" },
                    { identityType: "agency", resourceGroupId: "15" },
                ],
            }),
        ).toThrow(FormValidationError);
    });

    test("rejects invalid identity auto grant resource group id", () => {
        expect(() =>
            parseForm(resourceIdentityAutoGrantFormSchema, {
                items: [
                    { identityType: "host", resourceGroupId: "-1" },
                    { identityType: "bd", resourceGroupId: "12" },
                    { identityType: "bd_leader", resourceGroupId: "13" },
                    { identityType: "agency", resourceGroupId: "14" },
                    { identityType: "manager", resourceGroupId: "0" },
                ],
            }),
        ).toThrow(FormValidationError);
    });

    test("validates editable gift form fields", () => {
        const payload = parseForm(giftFormSchema, {
            chargeAssetType: "COIN",
            coinPrice: "10",
            effectTypes: ["animation"],
            effectiveFrom: "",
            effectiveTo: "",
            enabled: true,
            giftId: "rose",
            giftTypeCode: "normal",
            name: "Rose",
            presentationJson: "{}",
            priceVersion: "default",
            regionIds: ["0", "1001"],
            resourceId: "11",
            sortOrder: "0",
        });

        expect(payload.regionIds).toEqual(["0", "1001"]);
    });

    test("validates emoji pack category and pricing type", () => {
        const payload = parseForm(emojiPackFormSchema, {
            animationUrl: "https://media.haiyihy.com/emoji/wave.svga",
            category: "热门",
            coverUrl: "https://media.haiyihy.com/emoji/wave.png",
            name: "Wave",
            pricingType: "paid",
            regionIds: ["0"],
            sortOrder: "0",
        });

        expect(payload.category).toBe("热门");
        expect(payload.pricingType).toBe("paid");
    });

    test("validates resource grant form fields", () => {
        const payload = parseForm(resourceGrantFormSchema, {
            durationDays: "7",
            quantity: "1",
            reason: "manual",
            resourceIds: ["11", "12"],
            subjectType: "resource",
            targetUserId: "1001",
        });

        expect(payload.subjectType).toBe("resource");
        expect(payload.resourceIds).toEqual(["11", "12"]);
    });

    test("validates vip grant form fields", () => {
        const payload = parseForm(resourceGrantFormSchema, {
            reason: "manual",
            subjectType: "vip",
            targetUserId: "1001",
            vipLevel: "5",
        });

        expect(payload.subjectType).toBe("vip");
        expect(payload.vipLevel).toBe("5");
    });

    test("rejects invalid vip grant form fields", () => {
        const basePayload = {
            reason: "manual",
            subjectType: "vip",
            targetUserId: "1001",
            vipLevel: "5",
        };

        expect(() => parseForm(resourceGrantFormSchema, { ...basePayload, vipLevel: "" })).toThrow(FormValidationError);
        expect(() => parseForm(resourceGrantFormSchema, { ...basePayload, vipLevel: "bad" })).toThrow(FormValidationError);
        expect(() => parseForm(resourceGrantFormSchema, { ...basePayload, reason: "" })).toThrow(FormValidationError);
    });

    test("validates vip trial card level and duration", () => {
        const payload = parseForm(resourceGrantFormSchema, {
            durationDays: "20",
            reason: "manual",
            subjectType: "vip_trial_card",
            targetUserId: "1001",
            vipLevel: "5",
        });

        expect(payload.subjectType).toBe("vip_trial_card");
        expect(() => parseForm(resourceGrantFormSchema, { ...payload, durationDays: "0" })).toThrow(FormValidationError);
    });

    test("validates resource shop duration and price specifications", () => {
        const payload = parseForm(resourceShopItemsFormSchema, {
            items: [
                {
                    coinPrice: "100",
                    durationDays: "3",
                    effectiveFromMs: "",
                    effectiveToMs: "",
                    resourceId: "11",
                    sortOrder: "0",
                },
                {
                    coinPrice: "260",
                    durationDays: "7",
                    effectiveFromMs: "",
                    effectiveToMs: "",
                    resourceId: "11",
                    sortOrder: "0",
                },
            ],
        });

        expect(payload.items[0].durationDays).toBe("3");
        expect(payload.items[1].coinPrice).toBe("260");
        expect(() =>
            parseForm(resourceShopItemsFormSchema, {
                items: [
                    {
                        coinPrice: "100",
                        durationDays: "2",
                        effectiveFromMs: "",
                        effectiveToMs: "",
                        resourceId: "11",
                        sortOrder: "0",
                    },
                ],
            }),
        ).toThrow(FormValidationError);
        expect(() =>
            parseForm(resourceShopItemsFormSchema, {
                items: [
                    { coinPrice: "100", durationDays: "3", resourceId: "11" },
                    { coinPrice: "120", durationDays: "3", resourceId: "11" },
                ],
            }),
        ).toThrow(FormValidationError);
        expect(() =>
            parseForm(resourceShopItemsFormSchema, {
                items: [{ coinPrice: "0", durationDays: "1", resourceId: "11" }],
            }),
        ).toThrow(FormValidationError);
    });
});
