import { storeToRefs } from 'pinia'
import { useAuthStore } from '@/store/auth'
import { tokenService } from '@/services/api/token-service'

export default function useAuth() {
  const store = useAuthStore()
  const { user, role, isAuthenticated } = storeToRefs(store)

  const applySession = (payload = {}) => {
    if (payload.token) tokenService.saveToken(payload.token)
    if (payload.refreshToken) tokenService.saveRefreshToken(payload.refreshToken)
    if (payload.user) store.setUser(payload.user)
  }

  const savePhoneNumber = (phoneNumber) => {
    if (!phoneNumber) return
    const current = tokenService.getUserInfo() || {}
    if (!current.phone && !current.phoneNumber) {
      store.setUser({ ...current, phone: phoneNumber })
    }
  }

  const clearSession = () => {
    store.clearUser()
  }

  return {
    user,
    role,
    isAuthenticated,
    applySession,
    savePhoneNumber,
    clearSession,
  }
}
