const serverUrl = "http://localhost:8081";

export function createObject(_handle, _email, _password) {
    return {
        handle: _handle,
        email: _email,
        password: _password
    };
}

export async function getAllUsers() {
    const response = await fetch(`${serverUrl}/users`);
    if (!response.ok) {
        throw response.statusText;
    }
    return response.json();
}

export async function getUser(id) {
    const response = await fetch(`${serverUrl}/users/${id}`);
    if (!response.ok) {
        throw response.statusText;
    }
    console.log(response);
    return response.json();
}


export async function createUser(_handle, _email, _password) {
    const userObject = createObject(_handle, _email, _password);

    const options = {
        method: "POST",
        body: JSON.stringify(userObject),
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
        },
    };

    const response = await fetch(`${serverUrl}/users`, options);
    if (!response.ok) {
        throw response.statusText;
    }
    return response.json();
}

export async function updateUser(id, _handle, _email, _password) {
    const userObject = createObject(_handle, _email, _password);

    const options = {
        method: "PUT",
        body: JSON.stringify(userObject),
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
        },
    };

    const response = await fetch(`${serverUrl}/users/${id}`, options);
    if (!response.ok) {
        throw response.statusText;
    }
    return response.json();
}

export async function deleteUser(id) {
    const options = {
        method: "DELETE",
    };

    const response = await fetch(`${serverUrl}/users/${id}`, options);
    if (!response.ok) {
        throw response.statusText;
    }
    return response.json();
}