import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import http from '../api/http'

export interface CurrentUser {
  id: string
  userName: string
  displayName: string
  roles: string[]
  collegeId?: string
  effectiveDataScope: 'Self' | 'Class' | 'College' | 'All'
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref(localStorage.getItem('jiaowu_token') ?? '')
  const saved = localStorage.getItem('jiaowu_user')
  const user = ref<CurrentUser | null>(saved ? JSON.parse(saved) : null)
  const isLoggedIn = computed(() => Boolean(token.value))
  const isSuperAdmin = computed(() => user.value?.roles.includes('SuperAdmin') ?? false)

  async function login(userName: string, password: string) {
    const { data } = await http.post('/auth/login', { userName, password })
    token.value = data.token
    user.value = data.user
    localStorage.setItem('jiaowu_token', data.token)
    localStorage.setItem('jiaowu_user', JSON.stringify(data.user))
  }

  async function refresh() {
    if (!token.value) return
    const { data } = await http.get('/auth/me')
    user.value = data
    localStorage.setItem('jiaowu_user', JSON.stringify(data))
  }

  function logout() {
    token.value = ''
    user.value = null
    localStorage.removeItem('jiaowu_token')
    localStorage.removeItem('jiaowu_user')
  }

  return { token, user, isLoggedIn, isSuperAdmin, login, refresh, logout }
})
