import { defineStore } from 'pinia'
import { ref } from 'vue'
import { login as loginApi } from '@/api/auth'
import router from '@/router'

export type EntryMode = 'ops' | 'monitor'

export interface UserInfo {
  id: number
  name: string
  avatar: string
}

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem('token') || '')
  const user = ref<UserInfo | null>(parseStoredUser())
  const entryMode = ref<EntryMode>(parseStoredEntryMode())

  function parseStoredUser(): UserInfo | null {
    try {
      const stored = localStorage.getItem('user')
      return stored ? JSON.parse(stored) : null
    } catch {
      return null
    }
  }

  function parseStoredEntryMode(): EntryMode {
    const stored = localStorage.getItem('entryMode')
    return stored === 'monitor' ? 'monitor' : 'ops'
  }

  async function login(username: string, password: string) {
    const res = await loginApi(username, password)
    const data = res.data
    token.value = data.token
    user.value = {
      id: data.userVO.id,
      name: data.userVO.name,
      avatar: data.userVO.avatar,
    }
    localStorage.setItem('token', data.token)
    localStorage.setItem('user', JSON.stringify(user.value))
  }

  function setEntryMode(mode: EntryMode) {
    entryMode.value = mode
    localStorage.setItem('entryMode', mode)
  }

  function isMonitorMode(): boolean {
    return entryMode.value === 'monitor'
  }

  function logout() {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    router.push('/login')
  }

  function isLoggedIn(): boolean {
    return !!token.value
  }

  return { token, user, entryMode, login, logout, isLoggedIn, setEntryMode, isMonitorMode }
})
