import { ApiVoidResult } from "@core/Models/Api.VoidResult.type";
import ApiRequest from "@services/Api.Service";
import {
    CalculateCashFlowBalanceParams,
    CashFlowHistoryView,
    CreateCashFlowParams,
    DeleteMovementParams,
    FindCashFlowBalanceParams,
    ICashFlowBalance,
    PaginateCashFlowParams,
    PaginateCashFlowResults,
} from "@core/Models/CashFlow.model";
import { ApiError } from "@core/Models/Server.Error.model";
import * as Yup from "yup";

const schemaCreateCashFlowMovement = Yup.object().shape({
    paymentMethod: Yup.string().required("Debe introducir el tipo de movimiento."),
    companyId: Yup.string().required("La organización no es valida."),
    amount: Yup.number()
        .positive("El monto debe ser un número positivo.")
        .required("Debe introducir el monto del movimiento.")
        .typeError("El monto debe ser un número."),
    description: Yup.string().required("Debe introducir una descripción."),
    sessionUser: Yup.string().required("Para crear una organización debe iniciar sesión."),
});

export const createCashFlow = async (data: CreateCashFlowParams): Promise<ApiVoidResult> => {
    let yupErrors: Yup.ValidationError = new Yup.ValidationError("");
    const validateData = async () => {
        try {
            await schemaCreateCashFlowMovement.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<ApiVoidResult>("cashflow/create", data);
};

export const cashFlowCalculateBalance = async (
    data: CalculateCashFlowBalanceParams
): Promise<ICashFlowBalance> => {
    return ApiRequest.post<ICashFlowBalance>("cashflow/calculate-balance", data);
};

export const cashFlowDelete = async (data: DeleteMovementParams): Promise<ApiVoidResult> => {
    return ApiRequest.post<ApiVoidResult>("cashflow/delete", data);
};

export const cashFlowHistory = async (
    data: FindCashFlowBalanceParams
): Promise<CashFlowHistoryView> => {
    return ApiRequest.post<CashFlowHistoryView>("cashflow/history", data);
};

export const cashFlowPaginate = async (
    data: PaginateCashFlowParams
): Promise<PaginateCashFlowResults> => {
    return ApiRequest.post<PaginateCashFlowResults>("cashflow/paginate", data);
};

export const cashFlowPaginateBalance = async (data: FindCashFlowBalanceParams): Promise<number> => {
    return ApiRequest.post<number>("cashflow/paginate-balance", data);
};
