import axios, { AxiosError } from "axios";
import { ScorechainError } from "../types/errors/ScorchainError";
import { proofOfAuthenticityVerifierAdapterForAxios } from "./proofOfAuthenticityVerifier";

export async function _sendRequest<T>(
    url: string,
    method: string,
    data: object,
    headers: object,
    shouldVerifyAuthenticity?: boolean
): Promise<T> {
    const response = await axios
        .request<T>({
            url,
            method,
            data,
            headers,
        })
        .then(result => {
            if (shouldVerifyAuthenticity && !url.includes("publicKeys")) {
                proofOfAuthenticityVerifierAdapterForAxios(result);
            }
            return result;
        })
        .catch(error => {
            if (error instanceof AxiosError && (error as AxiosError)?.response?.data) {
                if (shouldVerifyAuthenticity) {
                    proofOfAuthenticityVerifierAdapterForAxios(error);
                }
                throw new ScorechainError(error);
            } else {
                throw error;
            }
        });

    return response.data;
}
