import { defineStore } from 'pinia'
import { LocalStorage } from 'quasar'
import { api } from 'boot/axios'
import { jwtDecode } from "jwt-decode"
import Router from 'src/router/index'

export const sessionName = 'bresSession'

const defaultState = {
  LoggedIn: false,
  IsAdmin: false,
  Token: '',
  UsrKSUID: '',
  UsrEmail: '',
  UsrFullname: '',
  Username: '',

  ClientKSUID: '',
  ClientCode: '',
  LicenseCode: '',
  PkgConf: {}
}

export const useLoginStore = defineStore('login', {
  state: () => {
    return JSON.parse(JSON.stringify(defaultState))
  },
  getters: {},
  actions: {

    login (payload) {
      // kaldıysa önceki session'ı uçuralım
      LocalStorage.remove(sessionName)
      const ds = JSON.parse(JSON.stringify(defaultState))
      Object.assign(this, ds)

      payload['LoggedIn'] = true
      const pl = JSON.parse(JSON.stringify(payload))
      Object.assign(this, pl)
      api.defaults.headers.common['Authorization'] = `Bearer ${payload.Token}`
      LocalStorage.set(sessionName, payload)
    },

    logout () {
      // todo: burada güvenlik zafiyeti var ! backend'de token invalidate edilmeli
      // bunun için memlist'e ek bir claim tutulabilir
      // ve jwtAuth verify koduna yazılıabilinir.
      // örnek : https://dev.to/stevensunflash/a-working-solution-to-jwt-creation-and-invalidation-in-golang-4oe4
      const ds = JSON.parse(JSON.stringify(defaultState))
      Object.assign(this, ds)

      api.defaults.headers.common['Authorization'] = ''
      LocalStorage.remove(sessionName)

      if (Router) {
        Router.push('/login')
        //router.push({ path: '/login', replace: true })
      }
    },

    updateState (payload) {
      Object.assign(this, payload)
      api.defaults.headers.common['Authorization'] = `Bearer ${payload.Token}`
    },

    load() {
      const authInfo = LocalStorage.getItem(sessionName)
      if (authInfo) {
        const decoded = jwtDecode(authInfo.Token)
        const now = Date.now() / 1000
        if (decoded.exp < now) {
          this.logout()
        } else {
          this.updateState(authInfo)
        }
      }
    },

    IsLoggedIn () {
        return this.LoggedIn
    }
  }
})

export default useLoginStore
