import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isLoggedIn: false,
    user: null,
    roles: [],
    role: null // Rückwärtskompatibilität: erste Rolle
  }),

  getters: {
    isAdmin: (state) => {
      return state.roles.includes('admin') || state.roles.includes('vorstand')
    },
    isNewsletter: (state) => {
      return state.roles.includes('newsletter')
    },
    hasRole: (state) => {
      return (role) => state.roles.includes(role)
    },
    hasAnyRole: (state) => {
      return (...roles) => roles.some(role => state.roles.includes(role))
    }
  },

  actions: {
    async checkAuth() {
      try {
        const response = await $fetch('/api/auth/status')
        this.isLoggedIn = response.isLoggedIn
        this.user = response.user
        this.roles = response.roles || (response.role ? [response.role] : [])
        this.role = response.role || (this.roles.length > 0 ? this.roles[0] : null) // Rückwärtskompatibilität
        return response
      } catch (_error) {
        this.isLoggedIn = false
        this.user = null
        this.roles = []
        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 passkeyLogin(email = '') {
      // Client-only
      if (typeof window === 'undefined' || !window.PublicKeyCredential || !window.isSecureContext) {
        throw new Error('Passkeys werden von diesem Browser nicht unterstützt.')
      }

      const normalizedEmail = String(email || '').trim().toLowerCase()

      const { options } = await $fetch('/api/auth/passkeys/authentication-options', {
        method: 'POST',
        body: normalizedEmail ? { email: normalizedEmail } : {}
      })

      const mod = await import('@simplewebauthn/browser')
      const credential = await mod.startAuthentication({ optionsJSON: options })

      const response = await $fetch('/api/auth/passkeys/login', {
        method: 'POST',
        body: { credential }
      })

      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.roles = []
        this.role = null
      } catch (error) {
        console.error('Logout fehlgeschlagen:', error)
        throw error
      }
    }
  }
})

