import { defineStore } from 'pinia'
import api from '../utils/request'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: null as any
  }),
  getters: {
    isAdmin: (state) => state.user?.role === 'SUPER_ADMIN'
  },
  actions: {
    async login(loginForm: any) {
      const response = await api.post('/auth/login/json', loginForm)
      this.token = response.data.access_token
      localStorage.setItem('token', this.token)
      await this.fetchUser()
    },
    async fetchUser() {
      const response = await api.get('/users/me')
      this.user = response.data
    },
    logout() {
      this.token = ''
      this.user = null
      localStorage.removeItem('token')
    }
  }
})

