import { defineStore } from 'pinia'
import { loginApi, getMe } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    user: null,
    loading: false,
  }),
  getters: {
    isLoggedIn: s => !!s.user,
    isSuperAdmin: s => s.user?.role === 'superadmin',
    isAdmin: s => s.user?.role === 'admin',
    isSeeker: s => s.user?.role === 'seeker',
  },
  actions: {
    async login(email, code) {
      const { data } = await loginApi({ email, code })
      localStorage.setItem('access_token', data.access)
      localStorage.setItem('refresh_token', data.refresh)
      await this.fetchMe()
    },
    async fetchMe() {
      const { data } = await getMe()
      this.user = data
    },
    logout() {
      localStorage.clear()
      this.user = null
    },
  },
})
