import { reactive } from 'vue'
import { call } from 'frappe-ui'

export const session = reactive({
  user: null,
  isLoggedIn: false,
  initialized: false,
  loading: true,

  async init() {
    if (this.initialized) {
      return
    }

    this.loading = true

    try {
      const data = await call('frappe.auth.get_logged_user')
      if (data && data !== 'Guest') {
        this.user = data
        this.isLoggedIn = true
      } else {
        this.user = null
        this.isLoggedIn = false
      }
    } catch (error) {
      console.error('Session init error:', error)
      this.user = null
      this.isLoggedIn = false
    }

    this.initialized = true
    this.loading = false
  },

  async logout() {
    try {
      await call('logout')
      this.user = null
      this.isLoggedIn = false
      this.initialized = false
      window.location.href = '/portal/login'
    } catch (error) {
      console.error('Logout error:', error)
    }
  },
})
