import { reactive } from 'vue'
import { memberLogin, getMemberProfile } from '@/api/member'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { joinApiUrl } from '@/config'

const state = reactive({
  token: getToken(),
  memberId: '',
  name: '',
  nickName: '',
  mobile: '',
  avatar: '',
  memberCode: ''
})

function isHttp(url) {
  return /^https?:\/\//i.test(url || '')
}

function resolveAvatar(path) {
  if (!path) return ''
  if (isHttp(path)) return path
  return joinApiUrl(path)
}

export function useUserStore() {
  /** 会员登录：account = 手机号或会员名称 */
  const login = (payload) => {
    const account = (payload.account || payload.username || '').trim()
    const password = payload.password
    const agreementAccepted = !!payload.agreementAccepted
    return memberLogin({ account, password, agreementAccepted }).then((res) => {
      // v1.3：与平台 /login 一致，token、memberId 在响应根级；兼容旧版 data 包裹
      const token = res.token || (res.data && res.data.token)
      const memberId = res.memberId != null && res.memberId !== ''
        ? res.memberId
        : (res.data && res.data.memberId)
      if (!token) {
        return Promise.reject(new Error('登录失败，未返回令牌'))
      }
      setToken(token)
      state.token = token
      state.memberId = memberId != null ? memberId : ''
      return res
    })
  }

  /** 会员资料 */
  const fetchUserInfo = () => {
    return getMemberProfile().then((res) => {
      const m = res.data || {}
      state.memberId = m.memberId
      state.memberCode = m.memberCode || ''
      state.name = m.memberCode || ''
      state.nickName = m.nickName || ''
      state.mobile = m.mobile || ''
      state.avatar = resolveAvatar(m.avatar)
      return res
    })
  }

  /** 本地退出（C 端会员暂无 logout 接口） */
  const logOut = () => {
    return fedLogOut()
  }

  const fedLogOut = () => {
    state.token = ''
    state.memberId = ''
    state.name = ''
    state.nickName = ''
    state.mobile = ''
    state.avatar = ''
    state.memberCode = ''
    removeToken()
    return Promise.resolve()
  }

  const displayName = () => state.nickName || state.memberCode || state.mobile || '会员'

  const isLoggedIn = () => !!state.token

  return {
    state,
    login,
    fetchUserInfo,
    logOut,
    fedLogOut,
    displayName,
    isLoggedIn
  }
}
