import { z } from "zod"

import { passwordValidator } from "@/utils/passwordValidator"
import { phoneValidator } from "@/utils/phoneValidator"

const countryRequiredMsg = "Country is required"
export const editProfileSchema = z
  .object({
    address: z.object({
      city: z.string().optional(),
      countryCode: z
        .string({
          required_error: countryRequiredMsg,
          invalid_type_error: countryRequiredMsg,
        })
        .min(1, countryRequiredMsg),
      streetAddress: z.string().optional(),
      zipCode: z.string().min(1, "Zip code is required"),
    }),
    dateOfBirth: z.string().min(1),
    email: z.string().email(),
    language: z.string(),
    phoneNumber: phoneValidator(
      "Phone is required",
      "Please enter a valid phone number"
    ),

    password: z.string().optional(),
    newPassword: z.literal("").optional().or(passwordValidator()),
    retypeNewPassword: z.string().optional(),
  })
  .superRefine((data, ctx) => {
    if (data.password) {
      if (!data.newPassword) {
        ctx.addIssue({
          code: "custom",
          message: "New password is required",
          path: ["newPassword"],
        })
      }
      if (!data.retypeNewPassword) {
        ctx.addIssue({
          code: "custom",
          message: "Retype new password is required",
          path: ["retypeNewPassword"],
        })
      }
    } else {
      if (data.newPassword || data.retypeNewPassword) {
        ctx.addIssue({
          code: "custom",
          message: "Current password is required",
          path: ["password"],
        })
      }
    }

    if (data.newPassword && !data.retypeNewPassword) {
      ctx.addIssue({
        code: "custom",
        message: "Retype new password is required",
        path: ["retypeNewPassword"],
      })
    }

    if (data.retypeNewPassword !== data.newPassword) {
      ctx.addIssue({
        code: "custom",
        message: "Retype new password does not match new password",
        path: ["retypeNewPassword"],
      })
    }
  })

export type EditProfileSchema = z.infer<typeof editProfileSchema>
