import { jwtDecode } from 'jwt-decode'

const TOKEN_KEY = 'scms_token'

export function readToken() {
  try {
    return localStorage.getItem(TOKEN_KEY)
  } catch {
    return null
  }
}

export function writeToken(token) {
  try {
    localStorage.setItem(TOKEN_KEY, token)
  } catch {
    // ignore
  }
}

export function clearToken() {
  try {
    localStorage.removeItem(TOKEN_KEY)
  } catch {
    // ignore
  }
}

export function decodeUser(token) {
  if (!token) return null
  try {
    const decoded = jwtDecode(token)
    return { id: decoded.id, username: decoded.username }
  } catch {
    return null
  }
}

