import { reactive } from 'vue'

const AUTH_KEY = 'mengyastore_auth'

const loadAuth = () => {
  try {
    const raw = localStorage.getItem(AUTH_KEY)
    if (!raw) return null
    return JSON.parse(raw)
  } catch {
    return null
  }
}

const saved = loadAuth()

export const authState = reactive({
  token:     saved?.token     || '',
  account:   saved?.account   || '',
  username:  saved?.username  || '',
  avatarUrl: saved?.avatarUrl || '',
  email:     saved?.email     || ''
})

export const isLoggedIn = () => !!authState.token

export const setAuth = (info) => {
  authState.token     = info.token     || ''
  authState.account   = info.account   || ''
  authState.username  = info.username  || ''
  authState.avatarUrl = info.avatarUrl || ''
  authState.email     = info.email     || ''
  localStorage.setItem(
    AUTH_KEY,
    JSON.stringify({
      token:     authState.token,
      account:   authState.account,
      username:  authState.username,
      avatarUrl: authState.avatarUrl,
      email:     authState.email
    })
  )
}

export const clearAuth = () => {
  authState.token     = ''
  authState.account   = ''
  authState.username  = ''
  authState.avatarUrl = ''
  authState.email     = ''
  localStorage.removeItem(AUTH_KEY)
}

export const getLoginUrl = () => {
  const redirectUri = `${window.location.origin}/auth/callback`
  const state = Math.random().toString(36).slice(2)
  return `https://auth.shumengya.top/?redirect_uri=${encodeURIComponent(redirectUri)}&state=${state}`
}
