//const backend = "http://localhost:7777";
const backend = "http://localhost:5000";

async function checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
        return response;
    }
    const error = new Error(response.statusText);
    const errorBody = await response.json();
    if (errorBody.errorMessage) {
        error.message = errorBody.errorMessage;
    } else {
        error.message = '';
    }
    throw error;
}

function postJson(endpoint, params) {
    return fetch(`${backend}${endpoint}`, {
        method: 'POST',
        // credentials: 'include',
        headers: {
            'Content-Type': 'application/json',
            Accept: 'application/json',
        },
        body: JSON.stringify(params),
    }).then(checkStatus);
}

function getJson(endpoint) {
    return fetch(`${backend}${endpoint}`, {
        method: 'GET',
        // credentials: 'include',
        headers: {
            Accept: '*',
        },
    }).then(checkStatus);
}

function parseJSON(response) {
    return response.json();
}

export function register(
    firstname,
    lastname,
    username,
    password
) {
    return postJson('/auth/register', {
        firstname,
        lastname,
        username,
        password,
    });
}

export function login(username, password) {
    return postJson('/auth/login', { username, password }).then(parseJSON);
}

export function signout() {
    return getJson('/auth/signout');
}

export function getCustomers(){
    return getJson(`/customers`);
}
