import ApiRequest from "@services/Api.Service";
import * as Yup from "yup";
import { ApiError } from "@core/Models/Server.Error.model";
import {
    CreateDiscountEmailParams,
    DeleteDiscountEmailParams,
    IDiscountEmail,
    PaginateDiscountsEmailParams,
    PaginateDiscountsEmailViewResults,
} from "@core/Models/DiscountsEmail.model";

const schemaDiscountEmailAdd = Yup.object().shape({
    email: Yup.string().email("Debe introducir un email válido").required("Debe introducir el email."),
    discountId: Yup.string().required("Debe introducir el código del descuento."),
    startDate: Yup.date().required("Debe introducir la fecha de inicio."),
    endDate: Yup.date().required("Debe introducir la fecha de fin."),
    sessionUser: Yup.string().required("Para crear un descuento debe iniciar sesión."),
});

export const createDiscountEmail = async (data: CreateDiscountEmailParams): Promise<IDiscountEmail> => {
    let yupErrors: Yup.ValidationError = new Yup.ValidationError("");

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

export const findDiscountsEmailByOrganization = async (
    data: PaginateDiscountsEmailParams
): Promise<PaginateDiscountsEmailViewResults> => {
    return ApiRequest.post<PaginateDiscountsEmailViewResults>("discounts-email/paginate", data);
};

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