import ApiRequest from "@services/Api.Service";
import * as Yup from "yup";
import { ApiError } from "@core/Models/Server.Error.model";
import {
    DeleteTemplateParams,
    FindTemplatesParams,
    GetDefaultTemplateParams,
    ITemplate,
    PaginateTemplatesParams,
    PaginateTemplatesResults,
    SaveTemplateParams,
} from "@core/Models/Templates.model";

const schemaTemplateSave = Yup.object().shape({
    templateId: Yup.string().optional(),
    companyId: Yup.string().required("No es posible deteriminar la organización."),
    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 el tipo de descuento."),
    template: Yup.string().required("Debe definir una plantilla."),
    sessionUser: Yup.string().required("Para crear un descuento debe iniciar sesión."),
});

export const saveTemplate = async (data: SaveTemplateParams): Promise<ITemplate> => {
    let yupErrors: Yup.ValidationError = new Yup.ValidationError("");

    const validateData = async () => {
        try {
            await schemaTemplateSave.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<ITemplate>("templates/save", data);
};

export const findTemplatesByOrganization = async (
    data: PaginateTemplatesParams
): Promise<PaginateTemplatesResults> => {
    return ApiRequest.post<PaginateTemplatesResults>("templates/paginate", data);
};

export const getTemplate = async (data: FindTemplatesParams): Promise<ITemplate> => {
    return ApiRequest.post<ITemplate>("templates/get", data);
};

export const getDefaultTemplate = async (data: GetDefaultTemplateParams): Promise<string> => {
    return ApiRequest.post<string>("templates/get-default", data);
};

export const deleteTemplate = async (data: DeleteTemplateParams): Promise<void> => {
    return ApiRequest.post<void>("templates/delete", data);
};
