import { defineStore } from 'pinia'
import { ref } from 'vue'
import { decodeJwtPayload, isJwtExpired } from '@/utils/jwt'

export interface UserInfo {
  id: string
  username: string
  nickname: string
  type: 'MAIN' | 'SUB'
}

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem('token'))
  const user = ref<UserInfo | null>(null)

  function setToken(t: string) {
    token.value = t
    localStorage.setItem('token', t)
    parseUser(t)
  }

  function parseUser(t: string) {
    try {
      const payload = decodeJwtPayload(t)
      if (!payload || isJwtExpired(t)) {
        throw new Error('token expired')
      }
      user.value = {
        id: String(payload.sub ?? ''),
        username: String(payload.username ?? ''),
        nickname: String(payload.nickname ?? ''),
        type: payload.type === 'SUB' ? 'SUB' : 'MAIN',
      }
    } catch {
      user.value = null
      token.value = null
      localStorage.removeItem('token')
    }
  }

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

  if (token.value) {
    parseUser(token.value)
  }

  return { token, user, setToken, logout }
})
