import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Agent, AuthResponse } from '@/types'
import { useApi } from '@/composables/useApi'

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('access_token'))
  const user = ref<Agent | null>(null)

  const api = useApi()

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

  async function login(username: string, password: string) {
    const response = await api.post<AuthResponse>('/auth/login', { username, password })
    // Set token BEFORE fetching user info (fetchUser needs the token for /auth/me)
    token.value = response.access_token
    localStorage.setItem('access_token', response.access_token)

    // Fetch user info
    await fetchUser()

    return response
  }

  async function register(username: string, password: string) {
    const response = await api.post<Agent>('/auth/register', { username, password })
    return response
  }

  async function fetchUser() {
    if (!token.value) return null
    try {
      user.value = await api.get<Agent>('/auth/me')
      return user.value
    } catch {
      logout()
      return null
    }
  }

  async function logout() {
    // Call backend logout endpoint, ignore errors
    try {
      await api.post('/auth/logout')
    } catch {
      // Ignore errors, proceed with local cleanup
    }
    token.value = null
    user.value = null
    localStorage.removeItem('access_token')
  }

  // Initialize user on store creation if token exists
  if (token.value) {
    fetchUser()
  }

  return {
    token,
    user,
    isAuthenticated,
    login,
    register,
    fetchUser,
    logout
  }
})
