import { computed, shallowRef } from 'vue'
import { defineStore } from 'pinia'
import type { User } from '@/types/api'
import { login as loginApi, me } from '@/api/auth'

export const useAuthStore = defineStore('auth', () => {
  const token = shallowRef(localStorage.getItem('qq_token') || '')
  const user = shallowRef<User | null>(null)

  const isAuthed = computed(() => Boolean(token.value))
  const isAdmin = computed(() => user.value?.role === 'admin')
  const permissionCodes = computed(() => new Set(user.value?.permissions?.map((item) => item.code) ?? []))

  function can(permission: string) {
    return user.value?.role === 'admin' || permissionCodes.value.has(permission)
  }

  async function login(email: string, password: string) {
    const response = await loginApi({ email, password })
    token.value = response.data.token
    user.value = response.data.user
    localStorage.setItem('qq_token', token.value)
  }

  async function loadMe() {
    if (!token.value) return
    const response = await me()
    user.value = response.data
  }

  function clearSession() {
    token.value = ''
    user.value = null
    localStorage.removeItem('qq_token')
  }

  return { token, user, isAuthed, isAdmin, permissionCodes, can, login, loadMe, clearSession }
})
