import { defineStore } from 'pinia'

export const useAuthStore = defineStore({
  id: 'AuthStore',
  state: () => ({ user: null, rentals: null, rent: {}, token: null }),
  persist: {
    storage: localStorage,
  },
  getters:{
    token(){
      return this.token
    }
  },
  actions: {
    async getData() {
      const { getToken } = useAuthToken()
      const { apiFetch } = useApi()
      const token = getToken()
      if (token) {
        this.token = token
        const { data } = await apiFetch('/me',
          {
            headers: {
              'auth-key': token
            }
          }
        )

        if (data.value?.user) {
          this.user = data.value.user
          this.rentals = data.value.rentals
        }
      }
    },
    async logout() {
      const { clearToken } = useAuthToken()
      await clearToken()
      this.user = null
      this.rentals = null
      this.token = null
      this.rent = {}
      navigateTo('/login')
    }
  }
})
