import { defineStore } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    access: null as string | null,
    refreshTokens: 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,
  }),
  
  persist: true, // TODO: Enable persistence. Cookies will be stored 'auth' 👉🏻 https://prazdevs.github.io/pinia-plugin-persistedstate/frameworks/nuxt
  // persist: {
  //   key: 'authentication-cookie',
  //   storage: piniaPluginPersistedstate.cookies({
  //     expires: 14, 
  //     sameSite: 'strict',
  //     secure: !import.meta.dev,
  //   }),
  //   paths: [
  //     'id',
  //     'name',
  //     'email',
  //     'role',
  //     'access',
  //     'refreshTokens',
  //     'cookiesAreAccepted',
  //   ],
  // },

  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 refreshAccessToken() {
      const config = useRuntimeConfig()
      if (!this.refreshTokens) return
      const data = await $fetch('/token/refresh/', {
        baseURL: config.public.baseURL,
        method: 'POST',
        body: { refresh: this.refreshTokens }
      })
      this.setPayload(data)
    },

    async logout() {
      this.$reset()
    },
    
    // Mutations migration
    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.refreshTokens = payload.refresh
      }
    }
  }
})
