import { reactive } from 'vue';
import api from '../api.js';

export const authState = reactive({
  checked: false,
  authenticated: false,
  user: null,
});

export async function checkAuth() {
  try {
    const { data } = await api.me();
    authState.authenticated = !!data.authenticated;
    authState.user = data.authenticated ? data : null;
  } catch (e) {
    authState.authenticated = false;
    authState.user = null;
  } finally {
    authState.checked = true;
  }
}

export async function login(username, password) {
  const { data } = await api.login(username, password);
  authState.authenticated = true;
  authState.user = data;
  return data;
}

export async function logout() {
  await api.logout();
  authState.authenticated = false;
  authState.user = null;
}
