interface UserState {
  username: string | null
  role: string | null
}

export const userStore = defineStore('user', {
  state: (): UserState => ({
    username: null,
    role: null,
  }),
  actions: {
    async login(username: string, password: string, ability: any) {
      try {
        const res = await $api(`${import.meta.env.VITE_API_BASE_URL}/auth/login`, {
          method: 'POST',
          body: {
            username,
            password,
          },
        })

        const { accessToken, userData, userAbilityRules: { rules } } = res

        this.username = username
        this.role = password === 'admin123' ? 'Admin' : 'Support'

        useCookie('accessToken').value = accessToken
        useCookie('userData').value = userData
        useCookie('userAbilityRules').value = rules
        ability.update(rules)
      }
      catch (err: any) {
        console.log(err.message)
        throw err // Rethrow the error so it can be caught in the component
      }
    },
    logout() {
      this.username = null
      this.role = null

      // Effacer les cookies
      useCookie('accessToken').value = null
      useCookie('userData').value = null
      useCookie('userAbilityRules').value = null
    },
  },
})
