import { defineStore } from 'pinia'
import { login, me, register } from '../api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    meLoaded: false,
    userId: 0,
    username: '',
    nickname: '',
    avatarPath: '',
    phone: '',
    email: '',
    gender: 0,
    roles: [],
  }),
  actions: {
    async login(req) {
      const res = await login(req)
      this.token = res.token
      localStorage.setItem('token', this.token)
      // Login response only has limited info, fetch full profile
      await this.fetchMe()
      return res
    },
    async register(req) {
      return register(req)
    },
    async fetchMe() {
      const res = await me()
      this.userId = res.userId
      this.username = res.username
      this.nickname = res.nickname || ''
      this.avatarPath = res.avatarPath || ''
      this.phone = res.phone || ''
      this.email = res.email || ''
      this.gender = res.gender || 0
      this.roles = res.roles || []
      this.meLoaded = true
      return res
    },
    logout() {
      this.token = ''
      localStorage.clear()
      this.meLoaded = false
      this.userId = 0
      this.username = ''
      this.nickname = ''
      this.avatarPath = ''
      this.phone = ''
      this.email = ''
      this.gender = 0
      this.roles = []
    },
  },
})

