import {api} from "./api";
import {requests} from "../../requests";

class AuthClient {

    async signOut() {
        localStorage.removeItem("token");
        return {};
    }

    async login(request, setLoading, setError, checkSession) {
        setLoading(true);
        const response = await api().post(requests.auth.login, request);

        if (response.data.error) {
            setError(response.data.error);
            setLoading(false);
            return;
        }

        localStorage.setItem("token", response.data.token);

        await checkSession?.();

        window.location.reload();
    }

    loginByCode(code, checkSession) {
        const request = {
            byLogin: false,
            code: code
        }
        api().post(requests.auth.login, request)
            .then(async (response) => {
                if (response.data.error) {
                    return;
                }
                localStorage.setItem("token", response.data.token);
                await checkSession?.();
                window.location.reload();
            })
    }
}

export const authClient = new AuthClient();
