import { z } from "zod";

export function createLoginSchema(messages: {
  emailRequired: string;
  emailInvalid: string;
  passwordRequired: string;
  passwordMin: string;
}) {
  return z.object({
    email: z
      .string()
      .min(1, messages.emailRequired)
      .email(messages.emailInvalid),
    password: z
      .string()
      .min(1, messages.passwordRequired)
      .min(8, messages.passwordMin),
  });
}

export function createRegisterSchema(messages: {
  emailRequired: string;
  emailInvalid: string;
  passwordRequired: string;
  passwordMin: string;
  confirmPasswordRequired: string;
  passwordMismatch: string;
  usernameInvalid?: string;
}) {
  return z
    .object({
      email: z
        .string()
        .min(1, messages.emailRequired)
        .email(messages.emailInvalid),
      username: z
        .string()
        .refine((val) => val === "" || /^[a-zA-Z0-9_-]{3,32}$/.test(val), {
          message: messages.usernameInvalid ?? "Invalid username",
        })
        .default(""),
      displayName: z.string().max(64).default(""),
      password: z
        .string()
        .min(1, messages.passwordRequired)
        .min(8, messages.passwordMin),
      confirmPassword: z.string().min(1, messages.confirmPasswordRequired),
    })
    .refine((data) => data.password === data.confirmPassword, {
      message: messages.passwordMismatch,
      path: ["confirmPassword"],
    });
}

export function createForgotPasswordSchema(messages: {
  emailRequired: string;
  emailInvalid: string;
}) {
  return z.object({
    email: z
      .string()
      .min(1, messages.emailRequired)
      .email(messages.emailInvalid),
  });
}

export function createResetPasswordSchema(messages: {
  passwordRequired: string;
  passwordMin: string;
  confirmPasswordRequired: string;
  passwordMismatch: string;
}) {
  return z
    .object({
      password: z
        .string()
        .min(1, messages.passwordRequired)
        .min(8, messages.passwordMin),
      confirmPassword: z.string().min(1, messages.confirmPasswordRequired),
    })
    .refine((data) => data.password === data.confirmPassword, {
      message: messages.passwordMismatch,
      path: ["confirmPassword"],
    });
}

export function createTwoFactorSchema(messages: {
  codeRequired: string;
  codeInvalid: string;
}) {
  return z.object({
    code: z
      .string()
      .min(1, messages.codeRequired)
      .regex(/^\d{6}$/, messages.codeInvalid),
  });
}

export type LoginFormValues = z.infer<ReturnType<typeof createLoginSchema>>;
export type RegisterFormValues = z.infer<ReturnType<typeof createRegisterSchema>>;
export type ForgotPasswordFormValues = z.infer<
  ReturnType<typeof createForgotPasswordSchema>
>;
export type ResetPasswordFormValues = z.infer<
  ReturnType<typeof createResetPasswordSchema>
>;
export type TwoFactorFormValues = z.infer<ReturnType<typeof createTwoFactorSchema>>;
