import { ApiVoidResult } from "@core/Models/Api.VoidResult.type";
import { DeleteCompanyParams } from "@core/Models/Company.model";
import ApiRequest from "@services/Api.Service";
import * as Yup from "yup";

const schema = Yup.object().shape({
    companyId: Yup.string().required("No se ha especificado una organización."),
    sessionUser: Yup.string().required(
        "No se ha podido determinar el usuario que intenta realizar esta acción"
    ),
});

interface ValidateErrorResult {
    status: boolean;
    error?: Yup.ValidationError;
}

const validateData = (data: DeleteCompanyParams): ValidateErrorResult => {
    let yupErrors: Yup.ValidationError = new Yup.ValidationError("");
    try {
        schema.validate(data, { abortEarly: true });
        return {
            status: true,
        };
    } catch (error) {
        if (error instanceof Yup.ValidationError) {
            yupErrors = error as Yup.ValidationError;
        }
        return {
            status: false,
            error: yupErrors,
        };
    }
};

export const deleteOrganization = async (data: DeleteCompanyParams): Promise<ApiVoidResult> => {
    const validation = validateData(data);

    if (validation.status == false) {
        throw new Error(validation.error?.message);
    }

    return ApiRequest.post<ApiVoidResult>("companies/delete", data);
};
