import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { getMe, logout as apiLogout } from '@/api'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const loading = ref(false)
  const authConfigured = ref(false)

  const isAuthenticated = computed(() => user.value !== null)
  const isAdmin = computed(() => user.value?.role === 'admin')

  function hasPermission(permission) {
    if (!user.value) return false
    if (user.value.role === 'admin') return true
    return (user.value.permissions || []).includes(permission)
  }

  async function fetchMe() {
    console.log('[auth] fetchMe start')
    loading.value = true
    try {
      user.value = await getMe()
      console.log('[auth] fetchMe success', user.value)
    } catch (err) {
      console.log('[auth] fetchMe error', err.message)
      if (err.message?.includes('401')) {
        user.value = null
      }
      // Swallow non-401 errors (network, 5xx) so the app stays usable
      // and doesn't flash the login screen on transient failures.
    } finally {
      loading.value = false
      console.log('[auth] fetchMe loading=false')
    }
  }

  const authEnabled = ref(true)

  async function fetchStatus() {
    console.log('[auth] fetchStatus start')
    try {
      const res = await fetch('/auth/status')
      console.log('[auth] fetchStatus response', res.status, res.ok)
      if (res.ok) {
        const data = await res.json()
        console.log('[auth] fetchStatus data', data)
        authEnabled.value = data.enabled !== false
        authConfigured.value = !!data.configured
        console.log('[auth] fetchStatus authEnabled set to', authEnabled.value)
        console.log('[auth] fetchStatus authConfigured set to', authConfigured.value)
      } else {
        console.log('[auth] fetchStatus not ok')
        authEnabled.value = true
        authConfigured.value = false
      }
    } catch (err) {
      console.log('[auth] fetchStatus error', err)
      authEnabled.value = true
      authConfigured.value = false
    }
  }

  function login() {
    const isAndroid = navigator.userAgent.includes('NaviAndroid')
    const params = new URLSearchParams()
    if (isAndroid) {
      params.set('platform', 'android')
    }
    const qs = params.toString()
    window.location.href = '/auth/login' + (qs ? '?' + qs : '')
  }

  async function logout() {
    try {
      await apiLogout()
    } catch {
      // ignore
    }
    user.value = null
    window.location.reload()
  }

  const isNoAuthMode = computed(() => !authEnabled.value)

  return {
    user,
    loading,
    authConfigured,
    authEnabled,
    isAuthenticated,
    isAdmin,
    isNoAuthMode,
    hasPermission,
    fetchMe,
    fetchStatus,
    login,
    logout,
  }
})
