import * as Yup from 'yup';

export const addPointValidationSchema = Yup.object({
  titleEndPoint: Yup.string().trim(),
  passengerId: Yup.string().trim(),

  establishmentId: Yup.number().when('passengerId', {
    is: (passengerId: string | undefined) =>
      !!passengerId && passengerId.trim() !== '',
    then: (schema) =>
      schema.required("Établissement est requis quand l'usager est rempli"),
    otherwise: (schema) => schema.notRequired(),
  }),

  establishment: Yup.string(),

  endPointAddress: Yup.object({
    address: Yup.string().required("L'adresse est requise"),
    lat: Yup.number(),
    lng: Yup.number(),
  }),
})
.test(
  'title-or-passenger',
  "Le titre du point ou l'usager doit être rempli",
  function (value) {
    const { titleEndPoint, passengerId } = value || {};

    const hasTitle =
      typeof titleEndPoint === 'string' && titleEndPoint.trim() !== '';
    const hasPassenger =
      typeof passengerId === 'string' && passengerId.trim() !== '';

    if (hasTitle || hasPassenger) {
      return true;
    }

    return this.createError({
      path: 'titleEndPoint',
      message:
        "Remplir soit le titre du point soit l'usager",
    });
  }
);
