import { defineStore } from 'pinia'

export const useAuthStore = defineStore({
  id: 'AuthStore',
  state: () => ({ user: null, rentals: null, rent: {} }),
  actions: {
    async getData() {
      const { getToken } = useAuthToken()
      const token = getToken()
      if (token) {
        const { data } = await useFetch('https://olcsoberauto.hu/rest/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.rent = {}
      navigateTo('/login')
    }
  }
})
