import { createApiClient } from "./axios";
import { tokenStore } from "./token";

// @ts-ignore
const authApi = createApiClient(import.meta.env.VITE_AUTH_BASE_URL);

export const authClient = {
  async login(username: string, password: string) {
    const res = await authApi.post("/login", { username, password });
    const { access_token } = res.data;

    if (!access_token) {
      throw new Error("No access token returned");
    }

    tokenStore.set(access_token);
    return this.getIdentity();
  },

  logout() {
    tokenStore.clear();
  },

  async getIdentity() {
    const res = await authApi.get("/me");
    return res.data;
  },

  isAuthenticated() {
    return !!tokenStore.get();
  },
};
