/**
 * 表单验证Schema
 */
import * as z from 'zod';
import { NotificationChannelType } from '../../types';

// 企业微信配置 Schema
const weworkConfigSchema = z.object({
  channelType: z.literal(NotificationChannelType.WEWORK),
  key: z.string()
    .min(1, '请输入Webhook Key')
    .regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i, '请输入有效的UUID格式Key'),
});

// 邮件配置 Schema
const emailConfigSchema = z.object({
  channelType: z.literal(NotificationChannelType.EMAIL),
  smtpHost: z.string().min(1, '请输入SMTP服务器地址'),
  smtpPort: z.number()
    .int('端口必须是整数')
    .min(1, '端口号必须大于0')
    .max(65535, '端口号不能超过65535'),
  username: z.string().min(1, '请输入用户名'),
  password: z.string().min(1, '请输入密码'),
  from: z.string().email('请输入有效的邮箱地址'),
  fromName: z.string().optional(),
  useSsl: z.boolean().optional(),
});

// 表单 Schema - 使用动态验证
export const formSchema = z.object({
  name: z.string().min(1, '请输入渠道名称').max(100, '渠道名称不能超过100个字符'),
  channelType: z.nativeEnum(NotificationChannelType),
  config: z.any(), // 先用 any，在 refine 中动态验证
  description: z.string().max(500, '描述不能超过500个字符').optional(),
}).refine((data) => {
  // 根据 channelType 动态验证 config
  if (data.channelType === NotificationChannelType.WEWORK) {
    return weworkConfigSchema.safeParse(data.config).success;
  } else if (data.channelType === NotificationChannelType.EMAIL) {
    return emailConfigSchema.safeParse(data.config).success;
  }
  return false;
}, {
  message: '配置信息不完整或格式错误',
  path: ['config'],
});

export type FormValues = z.infer<typeof formSchema>;
