import { defineStore } from 'pinia';
import { ID, account, functions, teams } from 'boot/appwrite';
import { ExecutionMethod, OAuthProvider, type Models } from 'appwrite';
import { computed, ref } from 'vue';

export const useAuthStore = defineStore('auth', () => {
  const currentUser = ref<Models.User<Models.Preferences> | null>(null);
  const currentUserTeams = ref<Models.TeamList<Models.Preferences> | null>(
    null
  );
  const userNames = ref<Record<string, string>>({});

  async function init() {
    try {
      currentUser.value = await account.get();
      currentUserTeams.value = await teams.list();
    } catch {
      currentUser.value = null;
      currentUserTeams.value = null;
    }
  }

  const currentUserTeamNames = computed(() =>
    currentUserTeams.value
      ? currentUserTeams.value.teams.map((team) => team.name)
      : []
  );

  const hasRequiredRole = (requiredRoles: string[]): boolean => {
    return requiredRoles.some((role) =>
      currentUserTeamNames.value.includes(role)
    );
  };

  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.createEmailPasswordSession(email, password);
    init();
  }

  async function googleLogin() {
    account.createOAuth2Session(
      OAuthProvider.Google,
      'https://bab.toal.ca/',
      'https://bab.toal.ca/#/login'
    );
    currentUser.value = await account.get();
  }

  function getUserNameById(id: string) {
    try {
      if (!userNames.value[id]) {
        userNames.value[id] = '';
        functions
          .createExecution(
            'userinfo',
            '',
            false,
            '/userinfo/' + id,
            ExecutionMethod.GET
          )
          .then((res) => {
            if (res.responseBody) {
              userNames.value[id] = JSON.parse(res.responseBody).name;
            } else {
              console.error(res, id);
            }
          });
      }
    } catch (e) {
      console.error('Failed to get username. Error: ' + e);
    }
    return userNames.value[id];
  }

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

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