/**
 * 认证表单校验
 *
 * 
 *
 * 业务行为：
 *   - validateEmail：使用 Zod (项目已有依赖) 校验邮箱格式
 *   - validatePassword：至少 8 位
 *   - validateUsername：3-20 位字母数字下划线
 *   - validateConfirmPassword：与 password 一致
 */
import { z } from "zod";

export const emailSchema = z.string().trim().email("Invalid email address");
export const passwordSchema = z
  .string()
  .min(8, "Password must be at least 8 characters");
export const usernameSchema = z
  .string()
  .trim()
  .min(3, "Username must be at least 3 characters")
  .max(20, "Username must be at most 20 characters")
  .regex(/^[a-zA-Z0-9_]+$/, "Username can only contain letters, numbers, and underscores");

export const validateEmail = (email: string): string | null => {
  const r = emailSchema.safeParse(email);
  return r.success ? null : r.error.issues[0]?.message ?? "Invalid email";
};

export const validatePassword = (password: string): string | null => {
  const r = passwordSchema.safeParse(password);
  return r.success ? null : r.error.issues[0]?.message ?? "Invalid password";
};

export const validateUsername = (username: string): string | null => {
  const r = usernameSchema.safeParse(username);
  return r.success ? null : r.error.issues[0]?.message ?? "Invalid username";
};

export const validateConfirmPassword = (
  password: string,
  confirmPassword: string,
): string | null => (password === confirmPassword ? null : "Passwords do not match");
