import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as loginApi, logout as logoutApi, getMe } from '@/api/auth.js'

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(null)
  const permissions = ref([])
  const menus = ref([])

  // Getters
  const isLoggedIn = computed(() => !!token.value)
  const isSuper = computed(() => userInfo.value?.is_super === true || userInfo.value?.is_super === 1)

  // Actions
  async function login(credentials) {
    const res = await loginApi(credentials)
    const { token: newToken } = res.data
    token.value = newToken
    // Only store token here — userInfo, permissions, menus
    // will be loaded by router guard via getInfo() which also
    // triggers dynamic route generation.
    localStorage.setItem('token', newToken)
    return res
  }

  async function getInfo() {
    const res = await getMe()
    const data = res.data
    // /auth/me returns flat structure: { id, username, ..., permissions, menus }
    userInfo.value = data
    permissions.value = data.permissions || []
    menus.value = data.menus || []
    return res
  }

  async function logout() {
    try {
      await logoutApi()
    } catch {
      // Ignore logout API errors — clear local state regardless
    } finally {
      token.value = ''
      userInfo.value = null
      permissions.value = []
      menus.value = []
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    }
  }

  function hasPermission(permCode) {
    if (isSuper.value) return true
    return permissions.value.includes(permCode)
  }

  return {
    token,
    userInfo,
    permissions,
    menus,
    isLoggedIn,
    isSuper,
    login,
    getInfo,
    logout,
    hasPermission
  }
})
