import { z } from "zod";

export const regionBlockKeywordSchema = z
    .string()
    .trim()
    .min(1, "请输入屏蔽词")
    .max(128, "屏蔽词不能超过 128 个字符");

export const regionBlockIPSchema = z
    .string()
    .trim()
    .min(1, "请输入 IP")
    .max(64, "IP 不能超过 64 个字符")
    .refine((value) => isIPv4(value) || isIPv6(value), "请输入正确的 IP 地址");

export const regionBlockUserIDSchema = z
    .string()
    .trim()
    .min(1, "请输入用户 ID/短 ID/靓号")
    .max(64, "用户 ID/短 ID/靓号不能超过 64 个字符")
    .refine((value) => !/\s/.test(value), "用户 ID/短 ID/靓号不能包含空白");

export const regionBlockReplaceSchema = z.object({
    keywords: z.array(regionBlockKeywordSchema).max(200, "最多配置 200 个屏蔽词"),
    whitelist_ips: z.array(regionBlockIPSchema).max(500, "最多配置 500 个白名单 IP"),
    whitelist_user_ids: z.array(regionBlockUserIDSchema).max(500, "最多配置 500 个白名单用户"),
});

export type RegionBlockReplaceForm = z.infer<typeof regionBlockReplaceSchema>;

function isIPv4(value: string) {
    const parts = value.split(".");
    return (
        parts.length === 4 &&
        parts.every((part) => {
            if (!/^\d{1,3}$/.test(part)) {
                return false;
            }
            const number = Number(part);
            return number >= 0 && number <= 255 && String(number) === part;
        })
    );
}

function isIPv6(value: string) {
    return value.includes(":") && /^[0-9a-fA-F:.]+$/.test(value) && value.split(":").length >= 3;
}
