import { z } from "zod"

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

export const editProfileErrors = {
  COUNTRY_REQUIRED: "COUNTRY_REQUIRED",
  ZIP_CODE_REQUIRED: "ZIP_CODE_REQUIRED",
  PHONE_REQUIRED: "PHONE_REQUIRED",
  PHONE_REQUESTED: "PHONE_REQUESTED",
  PASSWORD_NEW_REQUIRED: "PASSWORD_NEW_REQUIRED",
  PASSWORD_RETYPE_NEW_REQUIRED: "PASSWORD_RETYPE_NEW_REQUIRED",
  PASSWORD_CURRENT_REQUIRED: "PASSWORD_CURRENT_REQUIRED",
  PASSWORD_NEW_NOT_MATCH: "PASSWORD_NEW_NOT_MATCH",
} as const

export const editProfileSchema = z
  .object({
    address: z.object({
      city: z.string().optional(),
      countryCode: z
        .string({
          required_error: editProfileErrors.COUNTRY_REQUIRED,
          invalid_type_error: editProfileErrors.COUNTRY_REQUIRED,
        })
        .min(1, editProfileErrors.COUNTRY_REQUIRED),
      streetAddress: z.string().optional(),
      zipCode: z.string().min(1, editProfileErrors.ZIP_CODE_REQUIRED),
    }),
    dateOfBirth: z.string().min(1),
    email: z.string().email(),
    language: z.string(),
    phoneNumber: phoneValidator(
      editProfileErrors.PHONE_REQUIRED,
      editProfileErrors.PHONE_REQUESTED
    ),

    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: editProfileErrors.PASSWORD_NEW_REQUIRED,
          path: ["newPassword"],
        })
      }
      if (!data.retypeNewPassword) {
        ctx.addIssue({
          code: "custom",
          message: editProfileErrors.PASSWORD_RETYPE_NEW_REQUIRED,
          path: ["retypeNewPassword"],
        })
      }
    } else {
      if (data.newPassword || data.retypeNewPassword) {
        ctx.addIssue({
          code: "custom",
          message: editProfileErrors.PASSWORD_CURRENT_REQUIRED,
          path: ["password"],
        })
      }
    }

    if (data.newPassword && !data.retypeNewPassword) {
      ctx.addIssue({
        code: "custom",
        message: editProfileErrors.PASSWORD_RETYPE_NEW_REQUIRED,
        path: ["retypeNewPassword"],
      })
    }

    if (data.retypeNewPassword !== data.newPassword) {
      ctx.addIssue({
        code: "custom",
        message: editProfileErrors.PASSWORD_NEW_NOT_MATCH,
        path: ["retypeNewPassword"],
      })
    }
  })

export type EditProfileSchema = z.infer<typeof editProfileSchema>
