import { create } from 'zustand'
import api from '../api/client'
import { useSettingsStore } from './settings'

export const useAuthStore = create((set) => ({
  user: null,
  isAuthenticated: !!api.getToken(),
  loading: true,

  login: async (username, password) => {
    const data = await api.login(username, password)
    if (data.totp_required) {
      // Noch nicht eingeloggt — TOTP-Schritt nötig
      return data
    }
    set({ user: data.user, isAuthenticated: true })
    useSettingsStore.getState().fetchSettings()
    return data
  },

  validateTOTP: async (totpToken, code) => {
    const data = await api.validateTOTP(totpToken, code)
    set({ user: data.user, isAuthenticated: true })
    useSettingsStore.getState().fetchSettings()
    return data
  },

  logout: () => {
    api.logout()
    set({ user: null, isAuthenticated: false })
  },

  checkAuth: async () => {
    if (!api.getToken()) {
      set({ loading: false, isAuthenticated: false })
      return
    }
    try {
      const data = await api.me()
      set({ user: data.user || data, isAuthenticated: true, loading: false })
      useSettingsStore.getState().fetchSettings()
    } catch {
      api.logout()
      set({ user: null, isAuthenticated: false, loading: false })
    }
  },
}))
