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

export interface Authenticated {
  username: string
  password: string
  user: User
}

export type AuthenticationState = Authenticated | null

export const useAuthStore = defineStore('auth', () => {
  const state: Ref<AuthenticationState> = ref(null)
  const admin = computed(() => state.value && state.value.user.isAdmin)
  function logIn(username: string, password: string, user: User) {
    state.value = { username: username, password: password, user: user }
  }
  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)
  }
  return { state, admin, logIn, logOut, getBasicAuth }
})
