import { type AxiosResponse } from "axios"

export function useAPI(route: string = "/") {
    return `https://api.door.svitan.dev${route}`
}

export async function handleRequestError(error: unknown) {
    const toast = useToast()
    let message = undefined
    if (error instanceof Error) {
        message = error.message
    }

    toast.add({
        title: "Error occurred",
        description: message,
        color: "error",
    })
}

export function handleResponse<T extends { toString(): string }>(
    response: AxiosResponse<T>,
    success: (response: AxiosResponse<T>) => void = () => {}
) {
    const token = useToken()
    const toast = useToast()

    if (response.status === 200) {
        success(response)
    } else if (response.status === 401) {
        toast.add({ title: "Token not valid", color: "error" })
        token.value = ""
        navigateTo("/token")
    } else {
        toast.add({
            title: "Error occurred",
            description: response.data.toString(),
            color: "error",
        })
    }
}
