import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { authService, type AuthPayload, type RegisterPayload, type User } from '@/modules/auth/services/authService'

const storedUser = localStorage.getItem('auth_user')

export const useAuthStore = defineStore('auth', () => {
  const router = useRouter()
  const token = ref<string | null>(localStorage.getItem('auth_token'))
  const user = ref<User | null>(storedUser ? JSON.parse(storedUser) as User : null)
  const isAuthenticated = computed(() => Boolean(token.value))

  function persist(authToken: string, authUser: User) {
    token.value = authToken
    user.value = authUser
    localStorage.setItem('auth_token', authToken)
    localStorage.setItem('auth_user', JSON.stringify(authUser))
  }

  async function login(payload: AuthPayload, redirectTo = '/') {
    const data = await authService.login(payload)
    persist(data.token, data.user)
    await router.push(redirectTo)
  }

  async function register(payload: RegisterPayload, redirectTo = '/onboarding') {
    const data = await authService.register(payload)
    persist(data.token, data.user)
    await router.push(redirectTo)
  }

  async function logout() {
    if (token.value) {
      await authService.logout().catch(() => undefined)
    }

    token.value = null
    user.value = null
    localStorage.removeItem('auth_token')
    localStorage.removeItem('auth_user')
    localStorage.removeItem('current_company_id')
    await router.push('/login')
  }

  async function refreshUser() {
    if (!token.value) {
      return null
    }

    const authUser = await authService.me()
    setUser(authUser)

    return authUser
  }

  function setUser(authUser: User) {
    user.value = authUser
    localStorage.setItem('auth_user', JSON.stringify(authUser))
  }

  return {
    token,
    user,
    isAuthenticated,
    login,
    register,
    refreshUser,
    setUser,
    logout,
  }
})
