import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { kappa } from '@/services/kappa-api'
import { storage } from '@/services/storage'
import type { KappaLoginPayload } from '@/types/kappa'

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(storage.get('kappa_token'))
  const user = ref<{ name: string; email: string } | null>(storage.getJSON('kappa_user'))
  const loading = ref(false)
  const error = ref<string | null>(null)

  const isAuthenticated = computed(() => !!token.value)

  async function login(payload: KappaLoginPayload) {
    loading.value = true
    error.value = null
    try {
      const data = await kappa.login(payload)
      token.value = kappa['token']
      const name = data.full_name
        || `${data.first_name || ''} ${data.last_name || ''}`.trim()
        || 'Ricardo Gonzalez'
      user.value = { name, email: payload.email }
      await storage.setJSON('kappa_user', user.value)
      return true
    } catch (e: any) {
      error.value = e.message
      return false
    } finally {
      loading.value = false
    }
  }

  function logout() {
    kappa.logout()
    token.value = null
    user.value = null
    storage.remove('kappa_user')
  }

  return { token, user, loading, error, isAuthenticated, login, logout }
})
