import type { User } from '@/api/auth'
import { defineStore } from 'pinia'
import { ref, type Ref } from 'vue'

export interface Authenticated {
  username: string
  password: string
  user: User
  adminAsUser: User | null
}

export type AuthenticationState = Authenticated | null

export const useAuthStore = defineStore('auth', () => {
  const state: Ref<AuthenticationState> = ref(null)
  function logIn(username: string, password: string, user: User) {
    state.value = { username: username, password: password, user: user, adminAsUser: null }
  }
  function logOut() {
    state.value = null
  }
  function getBasicAuth() {
    if (!state.value) throw new Error('User is not authenticated.')
    return btoa(state.value.username + ':' + state.value.password)
  }
  function isAdmin() {
    return (
      state.value &&
      state.value.user.isAdmin &&
      (state.value.adminAsUser === null || state.value.adminAsUser.isAdmin)
    )
  }
  return { state, isAdmin, logIn, logOut, getBasicAuth }
})
