import { z } from "zod";

const displayUserIdSchema = z
    .string()
    .trim()
    .min(1, "请输入用户短 ID / 靓号")
    .refine((value) => Array.from(value).length <= 64, "用户短 ID / 靓号不能超过 64 个字符")
    // 靓号可能包含 Unicode 字形，不能收窄为纯数字；这里只拦截会破坏查询协议和日志的空白、控制字符。
    .refine((value) => !/[\s\p{Cc}]/u.test(value), "用户短 ID / 靓号不能包含空白或控制字符");

const usernameSchema = z
    .string()
    .trim()
    .min(3, "外管账号至少 3 位")
    .max(64, "外管账号不能超过 64 个字符")
    // 外管系统使用独立登录标识；限制为跨浏览器、网关和审计日志均稳定的 ASCII 账号字符集。
    .regex(/^[A-Za-z0-9._-]+$/, "外管账号只能包含字母、数字、点、下划线和连字符");

const permissionCodeSchema = z
    .string()
    .trim()
    .min(1, "权限编码不能为空")
    .max(128, "权限编码不能超过 128 个字符")
    .refine((value) => !/[\s\p{Cc}]/u.test(value), "权限编码不能包含空白或控制字符");

const permissionsSchema = z.array(permissionCodeSchema).max(200, "权限数量不能超过 200 项").transform((items) => [
    ...new Set(items),
]);

// 密码属于登录凭证，不能 trim 或自动改写；外管不设最小长度，但空值和全空白仍不可作为有效凭证。
const passwordSchema = z
    .string()
    .min(1, "请输入密码")
    .max(72, "密码不能超过 72 个字符")
    .refine((value) => value.trim().length > 0, "密码不能全部为空白字符");

export const externalAdminUserLookupSchema = z.object({
    displayUserId: displayUserIdSchema,
});

export const externalAdminUserCreateFormSchema = z
    .object({
        confirmPassword: passwordSchema,
        displayUserId: displayUserIdSchema,
        password: passwordSchema,
        permissions: permissionsSchema.optional(),
        username: usernameSchema,
    })
    .superRefine((value, context) => {
        if (value.password !== value.confirmPassword) {
            context.addIssue({ code: "custom", message: "两次输入的密码不一致", path: ["confirmPassword"] });
        }
    })
    .transform(({ confirmPassword: _confirmPassword, ...payload }) => payload);

export const externalAdminUserPasswordFormSchema = z
    .object({
        confirmPassword: passwordSchema,
        password: passwordSchema,
    })
    .superRefine((value, context) => {
        if (value.password !== value.confirmPassword) {
            context.addIssue({ code: "custom", message: "两次输入的密码不一致", path: ["confirmPassword"] });
        }
    })
    .transform(({ confirmPassword: _confirmPassword, ...payload }) => payload);

export const externalAdminUserStatusSchema = z.object({
    status: z.enum(["active", "disabled"]),
});

export const externalAdminUserPermissionsFormSchema = z.object({
    expectedRevision: z.number().int().positive("权限版本不正确"),
    // 空数组是明确的零权限快照，不能用默认权限替换，也不能在提交前过滤掉该字段。
    permissions: permissionsSchema,
});

export type ExternalAdminUserCreateForm = z.input<typeof externalAdminUserCreateFormSchema>;
export type ExternalAdminUserCreatePayload = z.output<typeof externalAdminUserCreateFormSchema>;
export type ExternalAdminUserPasswordForm = z.input<typeof externalAdminUserPasswordFormSchema>;
export type ExternalAdminUserPasswordPayload = z.output<typeof externalAdminUserPasswordFormSchema>;
export type ExternalAdminUserPermissionsForm = z.input<typeof externalAdminUserPermissionsFormSchema>;
export type ExternalAdminUserPermissionsPayload = z.output<typeof externalAdminUserPermissionsFormSchema>;
