import ApiRequest from "@services/Api.Service";
import * as Yup from "yup";
import { ApiError } from "@core/Models/Server.Error.model";
import {
    CreatePaymentParams,
    DeletePaymentParams,
    GetAppointmentPaymentsParams,
    IPayment,
    MarkAsPayedParams,
} from "@core/Models/Payments.model";

const schemaPaymentCreate = Yup.object().shape({
    appointmentId: Yup.string().required("Debe seleccionar un turno."),
    method: Yup.string().required("Debe seleccionar un método de pago."),
    status: Yup.string().required("Debe seleccionar estado para el pago."),
    amount: Yup.number()
        .positive()
        .required("Debe introducir un monto valido."),
    description: Yup.string().optional(),
    sessionUser: Yup.string().required(
        "Para crear un turno debe iniciar sesión."
    ),
});

export const createPayment = async (
    data: CreatePaymentParams
): Promise<IPayment> => {
    return new Promise<IPayment>((resolve, reject) => {
        schemaPaymentCreate
            .validate(data, { abortEarly: true })
            .then(() => {
                resolve(ApiRequest.post<IPayment>("payments/create", data));
            })
            .catch((error) => {
                reject(new ApiError(500, error.message));
            });
    });
};

export const getAppointmentPayments = async (
    data: GetAppointmentPaymentsParams
): Promise<IPayment[]> => {
    return new Promise<IPayment[]>((resolve) => {
        resolve(ApiRequest.post<IPayment[]>("payments/appointment", data));
    });
};

export const deletePayment = async (
    data: DeletePaymentParams
): Promise<void> => {
    return new Promise<void>((resolve) => {
        resolve(ApiRequest.post<void>("payments/delete", data));
    });
};

export const markAsPayed = async (data: MarkAsPayedParams): Promise<void> => {
    return new Promise<void>((resolve) => {
        resolve(ApiRequest.post<void>("payments/mark-as-payed", data));
    });
};
