import ApiRequest from "@services/Api.Service";
import {
    IAppointment,
    CreateAppointmentParams,
    FindAppointmentsParams,
    AppointmentAdminByDateView,
} from "@models/Appointments.model";

import * as Yup from "yup";
import { AddRepeatDisabledDateParams } from "@core/Models/Repeats.model";
import { ApiVoidResult } from "@core/Models/Api.VoidResult.type";

const schemaAppointmentAdd = Yup.object().shape({
    companyId: Yup.string().required("Debe seleccionar una organización."),
    serviceId: Yup.string().required("Debe seleccionar un servicio."),
    employeeId: Yup.string().required("Debe seleccionar un colaborador."),
    clientId: Yup.string().required("Debe seleccionar un cliente."),
    start: Yup.string().required("Debe seleccionar una fecha."),
    sessionUser: Yup.string().required("Para crear un turno debe iniciar sesión."),
});

export const createAppointment = async (data: CreateAppointmentParams): Promise<IAppointment> => {
    let yupErrors: Yup.ValidationError = new Yup.ValidationError("");

    const validateData = async () => {
        try {
            await schemaAppointmentAdd.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 Error(yupErrors.message);
    }

    return ApiRequest.post<IAppointment>("appointments/create", data);
};

export const findAppointmentsAdminByDate = async (
    data: FindAppointmentsParams
): Promise<AppointmentAdminByDateView> => {
    return ApiRequest.post<AppointmentAdminByDateView>("appointments/find-admin-by-date", data);
};

export const addDisabledRepeatDate = async (
    data: AddRepeatDisabledDateParams
): Promise<ApiVoidResult> => {
    return ApiRequest.post<ApiVoidResult>("repeats/add-disabled-date", data);
};
