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

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('token') || '')
  const username = ref('')

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

  async function login(user: string, password: string) {
    const res = await api.post('/auth/login', { username: user, password })
    token.value = res.data.access_token
    localStorage.setItem('token', token.value)
    username.value = user
  }

  function logout() {
    token.value = ''
    username.value = ''
    localStorage.removeItem('token')
  }

  async function fetchUser() {
    try {
      const res = await api.get('/auth/me')
      username.value = res.data.username
    } catch {
      logout()
    }
  }

  return { token, username, isAuthenticated, login, logout, fetchUser }
})
