import ApiRequest from "@services/Api.Service";
import * as Yup from "yup";
import { ApiError } from "@core/Models/Server.Error.model";
import {
    DeletePostParams,
    GetPostParams,
    IPost,
    PaginatePostsParams,
    PaginatePostsResults,
    SavePostParams,
} from "@core/Models/Posts.model";
import { FixCompanyPostParams, MoveCompanyFixedPostParams } from "@core/Models/Company.model";

const schemaPostSave = Yup.object().shape({
    postId: Yup.string().optional(),
    companyId: Yup.string().required("No es posible deteriminar la organización."),
    content: Yup.string().required("El post esta vacío."),
    fixed: Yup.boolean().optional(),
    fixedOrder: Yup.number().optional(),
    sessionUser: Yup.string().required("Para crear un descuento debe iniciar sesión."),
});

export const savePost = async (data: SavePostParams): Promise<IPost> => {
    let yupErrors: Yup.ValidationError = new Yup.ValidationError("");

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

export const findPostsByOrganization = async (
    data: PaginatePostsParams
): Promise<PaginatePostsResults> => {
    return ApiRequest.post<PaginatePostsResults>("posts/paginate", data);
};

export const getPost = async (
    data: GetPostParams
): Promise<IPost> => {
    return ApiRequest.post<IPost>("posts/get-post", data);
};

export const deletePost = async (data: DeletePostParams): Promise<void> => {
    return ApiRequest.post<void>("posts/delete", data);
};

export const toggleFixedPost = async (data: FixCompanyPostParams): Promise<void> => {
    return ApiRequest.post<void>("companies/toggle-fixed-post", data);
};

export const moveFixedPost = async (data: MoveCompanyFixedPostParams): Promise<void> => {
    return ApiRequest.post<void>("companies/move-fixed-post", data);
};
