import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useApi } from '../composables/useApi'
import type { Rider } from '../types/models'
import router from '../router'

interface AuthResponse {
  access_token: string
  token_type: string
  rider: Rider
}

export const useAuthStore = defineStore('auth', () => {
  const { api } = useApi()
  const token = ref<string | null>(localStorage.getItem('access_token'))
  const rider = ref<Rider | null>(null)
  const isAuthenticated = computed(() => !!token.value)

  function setAuth(response: AuthResponse) {
    token.value = response.access_token
    rider.value = response.rider
    localStorage.setItem('access_token', response.access_token)
  }

  function logout() {
    token.value = null
    rider.value = null
    localStorage.removeItem('access_token')
    router.push({ name: 'login' })
  }

  async function fetchRider() {
    if (!token.value) return
    try {
      const { data } = await api.get<Rider>('/rider/profile')
      rider.value = data
    } catch {
      // Token invalid — logout
      logout()
    }
  }

  async function updateRider(updates: Partial<Rider>) {
    const { data } = await api.put<Rider>('/rider/profile', updates)
    rider.value = data
    return data
  }

  async function loginWithTelegram(data: TelegramLoginData) {
    const { data: response } = await api.post<AuthResponse>('/auth/telegram-login', data)
    setAuth(response)
    router.push({ name: 'dashboard' })
  }

  async function loginWithWebApp(initData: string) {
    const { data: response } = await api.post<AuthResponse>('/auth/telegram-webapp', { init_data: initData })
    setAuth(response)
    router.push({ name: 'dashboard' })
  }

  return { token, rider, isAuthenticated, fetchRider, updateRider, loginWithTelegram, loginWithWebApp, logout }
})
