import { emailSchema } from "@/app/(auth)/_schema";
import { title } from "process";
import { InferType, array, boolean, number, object, string } from "yup";

export const addressN = object({
  address1: string().required("Address 1 is required"),
  address2: string().required("Address 2 is required"),
  town_city: string().required("Town city is required"),
  county: string().nullable(),
  country: string().required("Country is required"),
  post_code: string()
    .nullable()
    .typeError("Please enter correct post code")
    .required("Address is required"),
  primary: boolean(),
});

export const addressSchema = object({
  address: array().of(addressN).min(1, "At least one address is required"),
});

const phoneRegExp =
  /^((\\+[1-9]{1,4}[ \\-]*)|(\\([0-9]{2,3}\\)[ \\-]*)|([0-9]{2,4})[ \\-]*)*?[0-9]{3,4}?[ \\-]*[0-9]{3,4}?$/;

export const customerManageSchema = object({
  // customer_id: string(),
  first_name: string().required("First name is required"),
  last_name: string().required("Last name is required"),
  assigned_to_id: string(),
  title: string().required("Required"),
  DNC: boolean(),
  iso: string().required("Please add iso"),
  is_land_line_default: boolean().nullable(),
});

export const dncCheckerSchema = object()
  .shape({
    home_phone: string().matches(/^\d*$/, "Number is not valid").nullable(),
    mobile_phone: string()
      .matches(/^\d*$/, "Phone number is not valid")
      .nullable(),
    email: string()
      .matches(
        /^$|^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
        {
          message: "Please enter valid email",
        }
      )
      .nullable()
      .typeError("Please Enter Valid Email"),
  })
  .test(
    "at-least-one",
    "At least one of field1 or field2 is required",
    function (value): any {
      if (!value.home_phone && !value.mobile_phone) {
        return this.createError({
          path: "home_phone",
          message: "At least one of Landline or Mobile No. is required",
        });
      }
      return true;
    }
  );

// const schema = object()
//   .shape({
//     home_phone: string().matches(phoneRegExp, "Number is not valid"),
//     mobile_phone: string().matches(phoneRegExp, "Phone number is not valid"),
//   })
//   .test(
//     "at-least-one",
//     "At least one of field1 or field2 is required",
//     function (value): any {
//       return value.home_phone || value.mobile_phone;
//     }
//   );

export type DncCheckerSchemaT = InferType<typeof dncCheckerSchema>;
export type CustomerManageSchemaT = InferType<typeof customerManageSchema>;
export type AddressSchemaT = InferType<typeof addressSchema>;
export type AddressNSchemaT = InferType<typeof addressN>;

export type FormType = CustomerManageSchemaT &
  AddressSchemaT &
  DncCheckerSchemaT;
