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

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

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

export function createUser(user: User, onSuccess: () => void)
{
    axios.post(useRuntimeConfig().public.apiBase + '/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(useRuntimeConfig().public.apiBase + '/users/' + username + '/password', password, {
        headers: {
            Authorization: "Bearer " + requireToken(),
            "Content-Type": "text/plain"
        }
    })
    .then(() => {
        onSuccess();
    })
    .catch();
}