export function useAuth() {
  const config = useRuntimeConfig()
  const authStore = useAuthStore()

  // LexikJWT — POST /api/login_check → { token: string }
  async function login(email: string, password: string): Promise<void> {
    const data = await $fetch<{ token: string }>(
      `${config.public.apiBaseUrl}/login_check`,
      { method: 'POST', body: { username: email, password } }
    )
    authStore.setToken(data.token)
    await fetchCurrentUser()
  }

  // API Platform — GET /api/me → { id, email, roles, displayName }
  async function fetchCurrentUser(): Promise<void> {
    const user = await $fetch<{ id: number; email: string; roles: string[]; displayName?: string }>(
      `${config.public.apiBaseUrl}/me`,
      { headers: { Authorization: `Bearer ${authStore.token}` } }
    )
    authStore.setUser(user)
  }

  async function logout(): Promise<void> {
    authStore.logout()
    await navigateTo('/login')
  }

  return {
    login,
    logout,
    fetchCurrentUser,
    isAuthenticated: computed(() => authStore.isAuthenticated),
    isAdmin: computed(() => authStore.isAdmin),
    user: computed(() => authStore.user),
  }
}
