import ApiRequest from "@services/Api.Service";
import {
    IDiscount,
    PaginateDiscountsResults,
    CreateDiscountParams,
    PaginateDiscountsParams,
    DeleteDiscountParams,
    DiscountType,
} from "@models/Discounts.model";

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

const schemaDiscountAdd = Yup.object().shape({
    name: Yup.string().required("Debe introducir el nombre del descuento."),
    code: Yup.string().required("Debe introducir el código del descuento."),
    type: Yup.string().required("Debe seleccionar un tipo de descuento."),
    value: Yup.number()
        .required("Debe introducir un valor para el descuento.")
        .typeError("El valor debe ser un número."),
    sessionUser: Yup.string().required("Para crear un descuento debe iniciar sesión."),
});

export const createDiscount = async (data: CreateDiscountParams): Promise<IDiscount> => {
    let yupErrors: Yup.ValidationError = new Yup.ValidationError("");

    const validateData = async () => {
        try {
            await schemaDiscountAdd.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<IDiscount>("discounts/create", data);
};

export const findDiscountsByOrganization = async (
    data: PaginateDiscountsParams
): Promise<PaginateDiscountsResults> => {
    return ApiRequest.post<PaginateDiscountsResults>("discounts/paginate", data);
};

export const deleteDiscount = async (data: DeleteDiscountParams): Promise<void> => {
    return ApiRequest.post<void>("discounts/delete", data);
};

export const formatDiscountType = (type: string) => {
    switch (type) {
        case DiscountType.PERCENTAGE:
            return "Porcentaje";
        case DiscountType.FIXED:
            return "Monto";
    }
    return "n/a";
};
