import { z } from "zod";

export const signInSchema = z.object({
  email: z.string().trim().min(1, "Email is required").email("Enter a valid email address"),
  password: z.string().min(1, "Password is required").min(8, "Use at least 8 characters"),
});

export const signUpSchema = z
  .object({
    confirmPassword: z.string().min(1, "Confirm your password"),
    email: z.string().trim().min(1, "Email is required").email("Enter a valid email address"),
    name: z.string().trim().min(2, "Name must be at least 2 characters"),
    password: z.string().min(1, "Password is required").min(8, "Use at least 8 characters"),
  })
  .refine(({ confirmPassword, password }) => confirmPassword === password, {
    message: "Passwords do not match",
    path: ["confirmPassword"],
  });

export const getErrorMessage = (error: unknown): string | null => {
  if (!error) return null;
  if (typeof error === "string") return error;

  if (Array.isArray(error)) {
    for (const issue of error) {
      const message = getErrorMessage(issue);
      if (message) return message;
    }
    return null;
  }

  if (typeof error === "object" && error !== null && "message" in error) {
    const { message } = error as { message?: unknown };
    return typeof message === "string" ? message : null;
  }

  return null;
};
