import { z } from "zod";
import { validatePublicAppJumpParam } from "@/shared/app-jump/appJumpConfig.js";

const taskActionTypes = [
    "none",
    "wallet",
    "room",
    "room_random",
    "room_window",
    "room_random_window",
    "room_game",
    "room_random_game",
    "explore_game",
    "gift_panel",
    "gift_panel_specific",
] as const;

export const dailyTaskFormSchema = z
    .object({
        appJumpParam: z.string().trim().max(2048, "APP 跳转参数不能超过 2048 个字符").optional(),
        actionParam: z.string().trim().max(512, "跳转参数不能超过 512 个字符").optional(),
        actionType: z.enum(taskActionTypes),
        category: z.string().trim().max(32, "任务分类不能超过 32 个字符").optional(),
        description: z.string().trim().max(512, "描述不能超过 512 个字符"),
        effectiveFrom: z.string().optional(),
        effectiveTo: z.string().optional(),
        iconUrl: z.string().trim().max(512, "图标 URL 不能超过 512 个字符"),
        metricType: z.string().trim().min(1, "请输入指标类型").max(64, "指标类型不能超过 64 个字符"),
        rewardCoinAmount: z.union([z.string(), z.number()]),
        sortOrder: z.union([z.string(), z.number()]).optional(),
        status: z.enum(["draft", "active", "paused", "archived"]),
        targetUnit: z.enum(["count", "minute", "coin"]),
        targetValue: z.union([z.string(), z.number()]),
        taskType: z.enum(["daily", "exclusive"]),
        title: z.string().trim().min(1, "请输入任务名称").max(160, "任务名称不能超过 160 个字符"),
    })
    .superRefine((value, context) => {
        const targetValue = Number(value.targetValue);
        const rewardCoinAmount = Number(value.rewardCoinAmount);
        const sortOrder = Number(value.sortOrder || 0);
        const effectiveFromMs = datetimeLocalToMs(value.effectiveFrom);
        const effectiveToMs = datetimeLocalToMs(value.effectiveTo);

        if (!Number.isInteger(targetValue) || targetValue <= 0) {
            context.addIssue({ code: "custom", message: "请输入正整数目标值", path: ["targetValue"] });
        }
        if (!Number.isInteger(rewardCoinAmount) || rewardCoinAmount <= 0) {
            context.addIssue({ code: "custom", message: "请输入正整数奖励金币", path: ["rewardCoinAmount"] });
        }
        if (!Number.isInteger(sortOrder)) {
            context.addIssue({ code: "custom", message: "排序必须是整数", path: ["sortOrder"] });
        }
        if (effectiveFromMs < 0) {
            context.addIssue({ code: "custom", message: "请选择有效开始时间", path: ["effectiveFrom"] });
        }
        if (effectiveToMs < 0) {
            context.addIssue({ code: "custom", message: "请选择有效结束时间", path: ["effectiveTo"] });
        }
        if (effectiveFromMs > 0 && effectiveToMs > 0 && effectiveToMs <= effectiveFromMs) {
            context.addIssue({ code: "custom", message: "结束时间必须晚于开始时间", path: ["effectiveTo"] });
        }
        if (value.actionType !== "none") {
            const validation = validatePublicAppJumpParam(value.appJumpParam || "");
            if (!validation.valid) {
                context.addIssue({
                    code: "custom",
                    message: validation.message,
                    path: ["appJumpParam"],
                });
            }
        }
        if (!isJSONObject(value.appJumpParam)) {
            context.addIssue({
                code: "custom",
                message: "APP 跳转参数必须是对象格式",
                path: ["appJumpParam"],
            });
        }
    });

export type DailyTaskForm = z.infer<typeof dailyTaskFormSchema>;

function datetimeLocalToMs(value: unknown) {
    const trimmed = String(value || "").trim();
    if (!trimmed) {
        return 0;
    }
    const parsed = new Date(trimmed).getTime();
    return Number.isFinite(parsed) ? parsed : -1;
}

function isJSONObject(value: unknown) {
    const trimmed = String(value || "").trim();
    if (!trimmed) {
        return true;
    }
    try {
        const parsed = JSON.parse(trimmed);
        return Boolean(parsed) && !Array.isArray(parsed) && typeof parsed === "object";
    } catch {
        return false;
    }
}
