import axios from "axios";
import type { User } from "~/classes/User";

export function getUser(username: string, token: string, onSuccess: (user: User) => void)
{
    axios.get<User>(ApiConfig.getHttpBase() + '/users/' + username, {
        headers: {
            Authorization: "Bearer " + token
        }
    })
    .then((response) => {
        onSuccess(response.data);
    })
    .catch();
}

export function getUsers(onSuccess: (users: User[]) => void)
{
    axios.get<User[]>(ApiConfig.getHttpBase() + '/users', {
        headers: {
            Authorization: "Bearer " + requireToken()
        }
    })
    .then((response) => {
        onSuccess(response.data);
    })
    .catch();
}

export function createUser(user: User, onSuccess: () => void)
{
    axios.post(ApiConfig.getHttpBase() + '/users', user, {
        headers: {
            Authorization: "Bearer " + requireToken()
        }
    })
    .then(() => {
        onSuccess();
    })
    .catch();
}

export function changePassword(username: string | undefined, password: string, onSuccess: () => void)
{
    if(username == null)
    {
        throw new Error("[Method: changePassword] username is undefined.");
    }
    axios.put(ApiConfig.getHttpBase() + '/users/' + username + '/password', password, {
        headers: {
            Authorization: "Bearer " + requireToken(),
            "Content-Type": "text/plain"
        }
    })
    .then(() => {
        onSuccess();
    })
    .catch();
}