import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/api'

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('admin_token') || '')
  const user = ref(JSON.parse(localStorage.getItem('admin_user') || 'null'))

  const isLoggedIn = computed(() => !!token.value)

  async function login(username, password) {
    const res = await api.auth.login({ username, password })
    token.value = res.access_token
    user.value = res.admin_user
    localStorage.setItem('admin_token', res.access_token)
    localStorage.setItem('admin_user', JSON.stringify(res.admin_user))
    return res
  }

  function logout() {
    token.value = ''
    user.value = null
    localStorage.removeItem('admin_token')
    localStorage.removeItem('admin_user')
  }

  async function fetchUser() {
    if (!token.value) return
    try {
      const res = await api.auth.me()
      user.value = res
      localStorage.setItem('admin_user', JSON.stringify(res))
    } catch (e) {
      logout()
    }
  }

  return { token, user, isLoggedIn, login, logout, fetchUser }
})

