import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, getMe } from '@/api/auth'
import type { UserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const token = ref<string | null>(localStorage.getItem('dp_token') || null)
  const userInfo = ref<UserInfo | null>(null)
  const isLoggedIn = computed(() => !!token.value)

  // Extract role codes from user info
  const roleCodes = computed(() => {
    if (!userInfo.value?.roles) return []
    return userInfo.value.roles.map((r: any) => r.code)
  })

  const isSuperadmin = computed(() => roleCodes.value.includes('superadmin'))
  const isAdmin = computed(() => isSuperadmin.value || roleCodes.value.includes('admin'))
  const isManager = computed(() => isAdmin.value || roleCodes.value.includes('project_manager'))
  const isLabeler = computed(() => isManager.value || roleCodes.value.includes('labeler') || roleCodes.value.includes('reviewer'))

  function hasRole(code: string): boolean {
    return roleCodes.value.includes(code)
  }

  function hasAnyRole(codes: string[]): boolean {
    return codes.some((c) => roleCodes.value.includes(c))
  }

  async function login(username: string, password: string) {
    logout()
    const res = await apiLogin(username, password)
    token.value = res.access_token
    localStorage.setItem('dp_token', res.access_token)
    localStorage.setItem('dp_refresh', res.refresh_token)
    await fetchUserInfo()
    return res
  }

  async function fetchUserInfo() {
    if (!token.value) return null
    try {
      const res = await getMe()
      userInfo.value = res
      return res
    } catch (e: any) {
      // Don't logout on fetch error; token may still be valid
      console.error('Failed to fetch user info:', e?.message || e)
      // Only logout on 401
      if (e?.response?.status === 401 || e?.status === 401) {
        logout()
        throw e
      }
      return null
    }
  }

  function logout() {
    token.value = null
    userInfo.value = null
    localStorage.removeItem('dp_token')
    localStorage.removeItem('dp_refresh')
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    roleCodes,
    isSuperadmin,
    isAdmin,
    isManager,
    isLabeler,
    hasRole,
    hasAnyRole,
    login,
    fetchUserInfo,
    logout,
  }
})
