import ApiRequest from "@services/Api.Service";
import * as Yup from "yup";
import { ApiError } from "@core/Models/Server.Error.model";
import { FindAssistanceUserParams, UserAssistanceInfo } from "@core/Models/User.model";

const schemaGetUserAssistance = Yup.object().shape({
    email: Yup.string()
        .email("Debe ingresar un e-mail válido.")
        .required("Debe introducir el e-mail."),
    sessionUser: Yup.string().required("Debe iniciar sessión."),
});

export const getAssistanceUserInfo = async (
    data: FindAssistanceUserParams
): Promise<UserAssistanceInfo> => {
    let yupErrors: Yup.ValidationError = new Yup.ValidationError("");

    const validateData = async () => {
        try {
            await schemaGetUserAssistance.validate(data, { abortEarly: true });
            return true;
        } catch (error) {
            if (error instanceof Yup.ValidationError) {
                yupErrors = error as Yup.ValidationError;
            }
            return false;
        }
    };

    if ((await validateData()) == false) {
        throw new ApiError(400, yupErrors.message);
    }

    return ApiRequest.post<UserAssistanceInfo>("users/assistance-info", data);
};
