import { Axios } from 'axios';
import { consola } from 'consola/browser';
import type { User } from './models';


interface RequestError
{
    message: string;
}

class HeaptraderAPI
{
    private _axios: Axios;
    private _user?: User;

    constructor(baseURL: string = "http://localhost")
    {
        this._axios = new Axios({
            baseURL,
            withCredentials: true,
            withXSRFToken: true,
        });
    }

    async csrfCookie()
    {
        await this._axios.get("/sanctum/csrf-cookie");
    }

    async login(email: string, password: string): Promise<boolean>
    {
        await this.csrfCookie();
        const response = await this._axios.post<User | RequestError>("/login", { email, password });
        if (response.status === 200) {
            this._user = response.data as User;
            consola.info("Logged in as " + this._user.name);
            return true;
        } else {
            consola.error("Failed to log in: " + (response.data as RequestError).message);
            return false;
        }
    }

    user(): User | null
    {
        return this._user ?? null;
    }
}
