import { isExpired, parseSubject } from '@/api/token-util'
import { defineStore } from 'pinia'
import { ref, type Ref } from 'vue'

export interface AuthenticatedData {
  username: string
  token: string
}

const LOCAL_STORAGE_KEY = 'token'

export const useAuthStore = defineStore('auth', () => {
  const state: Ref<AuthenticatedData | null> = ref(getStateFromLocalStorage())

  function onUserLoggedIn(username: string, token: string) {
    state.value = { username, token }
    localStorage.setItem(LOCAL_STORAGE_KEY, token)
  }

  function onUserLoggedOut() {
    state.value = null
    localStorage.removeItem(LOCAL_STORAGE_KEY)
  }

  return { state, onUserLoggedIn, onUserLoggedOut }
})

function getStateFromLocalStorage(): AuthenticatedData | null {
  const token = localStorage.getItem(LOCAL_STORAGE_KEY)
  if (token === null || token.length === 0 || isExpired(token)) {
    localStorage.removeItem(LOCAL_STORAGE_KEY)
    return null
  }
  const username = parseSubject(token)
  console.info('Loaded authentication information for user', username)
  return { username, token }
}
