import { defineStore } from 'pinia';
import { ID, account } from 'boot/appwrite';
import type { Models } from 'appwrite';
import { ref } from 'vue';

export const useAuthStore = defineStore('auth', () => {
  const currentUser = ref<Models.User<Models.Preferences> | null>(null);
  const ready = ref(false);

  async function init() {
    try {
      currentUser.value = await account.get();
    } catch {
      currentUser.value = null;
    }
    ready.value = true;
  }

  async function register(email: string, password: string) {
    await account.create(ID.unique(), email, password);
    return await login(email, password);
  }
  async function login(email: string, password: string) {
    await account.createEmailSession(email, password);
    currentUser.value = await account.get();
  }
  async function googleLogin() {
    account.createOAuth2Session(
      'google',
      'https://bab.toal.ca/',
      'https://bab.toal.ca/#/login'
    );
    currentUser.value = await account.get();
  }

  function logout() {
    return account.deleteSession('current').then((currentUser.value = null));
  }

  return { currentUser, register, login, googleLogin, logout, init, ready };
});
