import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isLoggedIn: false,
    user: null,
    role: null
  }),

  getters: {
    isAdmin: (state) => {
      return state.role === 'admin' || state.role === 'vorstand'
    }
  },

  actions: {
    async checkAuth() {
      try {
        const response = await $fetch('/api/auth/status')
        this.isLoggedIn = response.isLoggedIn
        this.user = response.user
        this.role = response.role
        return response
      } catch (error) {
        this.isLoggedIn = false
        this.user = null
        this.role = null
        return { isLoggedIn: false }
      }
    },

    async login(email, password) {
      const response = await $fetch('/api/auth/login', {
        method: 'POST',
        body: { email, password }
      })
      
      if (response.success) {
        await this.checkAuth()
      }
      
      return response
    },

    async logout() {
      try {
        await $fetch('/api/auth/logout', { method: 'POST' })
        this.isLoggedIn = false
        this.user = null
        this.role = null
      } catch (error) {
        console.error('Logout fehlgeschlagen:', error)
        throw error
      }
    }
  }
})

