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

import * as Yup from "yup";
import { ApiError } from "@core/Models/Server.Error.model";

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."),
    userId: Yup.string().required("Para crear un turno debe iniciar sesión."),
    start: Yup.string().required("Debe seleccionar una fecha."),
    sessionUser: Yup.string().required("Para crear un turno debe iniciar sesión."),
});

const schemaGetAvailableDates = 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."),
    length: Yup.number().max(60).min(1).required("No se ha especificado un periodo de busqueda."),
    sessionUser: Yup.string().required("Para crear un turno debe iniciar sesión."),
});

export const createAppointment = async (data: CreateAppointmentParams): Promise<IAppointment> => {
    return new Promise<IAppointment>((resolve, reject) => {
        schemaAppointmentAdd
            .validate(data, { abortEarly: true })
            .then(() => {
                resolve(ApiRequest.post<IAppointment>("appointments/create", data));
            })
            .catch((error) => {
                reject(new ApiError(500, error.message));
            });
    });
};

export const getAvailableDates = async (
    data: GetAvailableDatesParams
): Promise<GetAvailableDatesResult> => {
    return new Promise<GetAvailableDatesResult>((resolve, reject) => {
        schemaGetAvailableDates
            .validate(data, { abortEarly: true })
            .then(() => {
                resolve(
                    ApiRequest.post<GetAvailableDatesResult>(
                        "appointments/get-available-dates",
                        data
                    )
                );
            })
            .catch((error) => {
                reject(new ApiError(500, error.message));
            });
    });
};
