import * as yup from "yup";

export const isValidPhoneNumber = (value: string, context: any) => {
  const minLength = context.parent.minPhoneLength;

  if (!value || value.length == 0 || value.length < minLength) return false;

  return true;
};

export const isValidPostalCode = (value: string, context: any) => {
  const { parent } = context;
  const zipCodeRegex = parent.zipCodeRegex;

  // Ensure the regex exists and is valid
  if (zipCodeRegex.length == 0) {
    return true;
  }

  const regex = new RegExp(zipCodeRegex);
  return regex.test(value);
};

export const AddressShippingSchema = () => {
  return yup.object({
    firstName: yup
      .string()
      .min(2, "First Name is required")
      .required("First Name is required"),
    lastName: yup.string().min(2).required("Last Name is required"),
    address: yup.string().min(2).max(35).required("Address is required"),
    buildingInfo: yup.string().max(100),
    countryId: yup.number().required("Select country is required"),
    state: yup.string().required("Select state is required"),
    city: yup.string().required("Select city is required"),
    postalCode: yup
      .string()
      .min(4)
      .max(10)
      .required("Zipcode field is required")
      .test("is-postal-code-valid", "Invalid Postal Code", (value, context) =>
        isValidPostalCode(value, context),
      ),
    phone: yup
      .string()
      .min(2)
      .max(12)
      .required("Enter Mobile Number it is required")
      .test("is-phone-number-valid", "Invalid Phone Number", (value, context) =>
        isValidPhoneNumber(value, context),
      ),
    // zipCodeRegex: yup.string(),
    // zipCodeExample: yup.string(),
    minPhoneLength: yup.string(),
  });
};
