import { z } from "zod";

export const signupSchema = z
  .object({
    firstName: z
      .string()
      .trim()
      .nonempty("First Name is required")
      .min(3, "First Name must be at least 3 characters")
      .max(50, "First Name cannot exceed 50 characters")
      .regex(
        /^[A-Za-z]+(?: [A-Za-z]+)?$/,
        "First Name can only contain letters and at most one space",
      ),

    lastName: z
      .string()
      .trim()
      .nonempty("Last Name is required")
      .min(3, "Last Name must be at least 3 characters")
      .max(50, "Last Name cannot exceed 50 characters")
      .regex(
        /^[A-Za-z]+(?: [A-Za-z]+)?$/,
        "Last Name can only contain letters and at most one space",
      ),
    mobileNumber: z.object({
      dialCode: z.string().min(1, "Dial code is required"),
      number: z
        .string()
        .min(10, "Mobile number cannot be less than 10 digits")
        .max(15, "Mobile number cannot be more than 15 digits"),
    }),
    email: z
      .string()
      .trim()
      .min(1, "Please enter your email address")
      .email("Please enter a valid email address (e.g. john@example.com)")
      .refine((email) => {
        const [, domain] = email.split("@");

        if (!domain) return false;

        const labels = domain.split(".");

        return labels.every(
          (label) =>
            label.length > 0 && !label.startsWith("-") && !label.endsWith("-"),
        );
      }, "Please enter a valid email address (e.g. john@example.com)"),
    password: z
      .string()
      .min(1, "Password is required")
      .refine(
        (value) =>
          /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/.test(value),
        {
          message:
            "Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one number, and one special character.",
        },
      ),
    confirmPassword: z
      .string()
      .min(1, "Confirm Password is required")
      .refine(
        (value) =>
          /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^A-Za-z0-9]).{8,}$/.test(value),
        {
          message:
            "Password must be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one number, and one special character.",
        },
      ),
  })
  .superRefine((data, ctx) => {
    if (data.password !== data.confirmPassword) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        message: "Passwords do not match",
        path: ["confirmPassword"],
      });
    }
  });
export type SignupSchema = z.infer<typeof signupSchema>;
