import { createBasicHeader, setAuthHeader, setContentTypeHeaderJson } from "./headers";

export async function get(url: string) : Promise<Response>{
    const requestHeaders = createBasicHeader();
    setAuthHeader(requestHeaders);
    console.log("GET to " + url);
    const response = await fetch(url, {
        method: "GET",
        headers: requestHeaders
    })
    if(!response.ok){
        throw new Error("GET to " + url + " failed with " + response.status + " " + response.statusText);
    }
    return response;
}

export async function postJson(url: string, requestBody: string, logBody = true) : Promise<Response>{
    console.log("POST to " + url);
    if(logBody){
        console.log("body: " + requestBody);
    }
    return await persistJson(url, requestBody, "POST");
}

async function persistJson(url: string, requestBody: string, requestMethod: string) : Promise<Response>{
    const requestHeaders = createBasicHeader();
    setContentTypeHeaderJson(requestHeaders);
    setAuthHeader(requestHeaders);
    const request = new Request(url, {
        method: requestMethod,
        headers: requestHeaders,
        body: requestBody,
    });
    console.log(request)
    const response = await fetch(request);
    console.log("response.ok", response.ok)
    if(!response.ok){
        throw new Error(requestMethod + " to " + url + " failed " + response.status + " " + response.statusText);
    }
    return response;
}


