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 enum LogoutReason {
  USER_LOGGED_OUT,
  INACTIVITY_TIMEOUT,
  TOKEN_EXPIRED,
}

export const useAuthStore = defineStore('auth', () => {
  console.log('Initializing authStore')

  const state: Ref<AuthenticatedData | null> = ref(getStateFromLocalStorage())
  const logoutReason: Ref<LogoutReason | null> = ref(null)

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

  function onUserLoggedOut(reason: LogoutReason) {
    state.value = null
    logoutReason.value = reason
    localStorage.removeItem(LOCAL_STORAGE_KEY)
  }

  return { state, logoutReason, 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)
  return { username, token }
}
