// stores/auth.ts
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    access: null as string | null,
    refresh: null as string | null,
    id: null as number | null,
    name: null as string | null,
    email: null as string | null,
    role: 'ANON' as string,
    cookiesAreAccepted: false,
  }),
  getters: {
    isAuthenticated: (state) => !!state.access,
    isUser: (state) => state.role === 'SHOP_USER',
    isManager: (state) => state.role === 'COOP_MANAGER',
    isAdmin: (state) => state.role === 'SITE_ADMIN',
    getName: (state) => state.name,
    getId: (state) => state.id,
    cookiesAccepted: (state) => state.cookiesAreAccepted,
  },
  actions: {
    // Actions to handle authentication (action's migration)
    async login(email: string, password: string) {
      const config = useRuntimeConfig()
      const payload = await $fetch('/token/', {
        baseURL: config.public.baseURL,
        method: 'POST',
        body: { email, password }
      })
      //console.log('Login payload:', payload)
      this.setPayload(payload)
    },

    async setUser() {
      const config = useRuntimeConfig()
      const data = await $fetch('/my_user/', {
        baseURL: config.public.baseURL,
        method: 'GET',
        headers: {
          Authorization: `Bearer ${this.access}`
        }
      })
      try {
        this.setUserData(data)
      } catch (error) {
        console.error('Error setting user data:', error)
      }
    },

    async refresh() {
      const config = useRuntimeConfig()
      if (!this.refresh) return
      const data = await $fetch('/token/refresh/', {
        baseURL: config.public.baseURL,
        method: 'POST',
        body: { refresh: this.refresh }
      })
      this.setPayload(data)
    },

    // Mutations migration
    logout() {
      this.$reset() // Reset the store state
    },

    acceptCookies() {
      this.cookiesAreAccepted = true
    },

    setUserData(payload: any) {
      this.id = payload.id
      this.name = payload.full_name
      this.email = payload.email
      this.role = payload.role
    },

    setPayload(payload: any) {
      this.access = payload.access
      if (payload.refresh) {
        this.refresh = payload.refresh
      }
    }
  }
})
