import * as Yup from "yup";

interface ValidationResult<T> {
  isValid: boolean;
  errors: Partial<Record<keyof T, string>> | null;
}

export const validationWithMessages = async <T extends object>(
  yupObjectShape: Yup.ObjectShape,
  data: T
): Promise<ValidationResult<T>> => {
  const schema = Yup.object().shape(yupObjectShape);
  
  const isValid = await schema.isValid(data, {
    abortEarly: false, // Evitar que se detenga la validación tras el primer error
  });

  let errors: Partial<Record<keyof T, string>> | null = null;

  if (!isValid) {
    errors = await schema.validate(data, { abortEarly: false }).catch((err) => {
      // Recoger todos los errores en formato { fieldName: string }
      return err.inner.reduce((acc: Partial<Record<keyof T, string>>, error: Yup.ValidationError) => {
        return {
          ...acc,
          [error.path as keyof T]: error.errors[0],
        };
      }, {});
    });
  }

  return {
    isValid,
    errors,
  };
};
