import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/api/client'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const tenant = ref(null)
  const accessToken = ref(localStorage.getItem('access_token') || null)
  const refreshToken = ref(localStorage.getItem('refresh_token') || null)

  const isAuthenticated = computed(() => !!accessToken.value)
  
  const isPlatformAdmin = computed(() => user.value?.type === 'platform_admin')
  
  const isTenantAdmin = computed(() => user.value?.user_type === 'admin')

  async function login(email, password) {
    try {
      const response = await api.post('/auth/login', { email, password })
      const { data } = response.data
      
      accessToken.value = data.access_token
      refreshToken.value = data.refresh_token
      
      localStorage.setItem('access_token', data.access_token)
      localStorage.setItem('refresh_token', data.refresh_token)
      
      await fetchUser()
      
      return { success: true }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.message || 'Login failed' 
      }
    }
  }

  async function register(payload) {
    try {
      const response = await api.post('/auth/register', payload)
      return { success: true, data: response.data.data }
    } catch (error) {
      return { 
        success: false, 
        message: error.response?.data?.message || 'Registration failed',
        errors: error.response?.data?.errors || {}
      }
    }
  }

  async function fetchUser() {
    try {
      const response = await api.get('/auth/me')
      user.value = response.data.data
      
      if (user.value.tenant_id) {
        tenant.value = {
          id: user.value.tenant_id,
          name: user.value.tenant_name,
          slug: user.value.tenant_slug,
          status: user.value.tenant_status,
          primary_color: user.value.primary_color,
          secondary_color: user.value.secondary_color,
        }
      }
    } catch (error) {
      console.error('Failed to fetch user:', error)
      logout()
    }
  }

  async function refreshAccessToken() {
    if (!refreshToken.value) return false
    
    try {
      const response = await api.post('/auth/refresh', {
        refresh_token: refreshToken.value
      })
      
      const { data } = response.data
      accessToken.value = data.access_token
      refreshToken.value = data.refresh_token
      
      localStorage.setItem('access_token', data.access_token)
      localStorage.setItem('refresh_token', data.refresh_token)
      
      return true
    } catch (error) {
      logout()
      return false
    }
  }

  function logout() {
    user.value = null
    tenant.value = null
    accessToken.value = null
    refreshToken.value = null
    
    localStorage.removeItem('access_token')
    localStorage.removeItem('refresh_token')
  }

  // Initialize
  if (accessToken.value) {
    fetchUser()
  }

  return {
    user,
    tenant,
    accessToken,
    refreshToken,
    isAuthenticated,
    isPlatformAdmin,
    isTenantAdmin,
    login,
    register,
    fetchUser,
    refreshAccessToken,
    logout
  }
})