import type { Profile } from '@/api/profile'
import { defineStore } from 'pinia'
import { ref, type Ref } from 'vue'

const LOCAL_STORAGE_KEY = 'profile'

export const useProfileStore = defineStore('profile', () => {
  const state: Ref<Profile | null> = ref(getStateFromLocalStorage())

  function onProfileSelected(profile: Profile) {
    state.value = profile
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(profile))
  }

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

  return { state, onProfileSelected, onProfileSelectionCleared }
})

function getStateFromLocalStorage(): Profile | null {
  const jsonText = localStorage.getItem(LOCAL_STORAGE_KEY)
  if (jsonText === null || jsonText.length === 0) {
    localStorage.removeItem(LOCAL_STORAGE_KEY)
    return null
  }
  const profile = JSON.parse(jsonText) as Profile
  console.info('Loaded profile', profile)
  return profile
}
