const WORKER_TOKEN_KEY = 'order-site-worker-token'
const WORKER_EXPIRES_AT_KEY = 'order-site-worker-token-expires-at'
const WORKER_ID_KEY = 'order-site-worker-id'
const WORKER_USERNAME_KEY = 'order-site-worker-username'
const WORKER_STATUS_KEY = 'order-site-worker-status'

export function getWorkerToken() {
  return localStorage.getItem(WORKER_TOKEN_KEY) || ''
}

export function getWorkerTokenExpiresAt() {
  return localStorage.getItem(WORKER_EXPIRES_AT_KEY) || ''
}

export function getWorkerId() {
  const value = Number(localStorage.getItem(WORKER_ID_KEY) || 0)
  return Number.isFinite(value) && value > 0 ? value : 0
}

export function getWorkerUsername() {
  return localStorage.getItem(WORKER_USERNAME_KEY) || ''
}

export function getWorkerStatus() {
  return localStorage.getItem(WORKER_STATUS_KEY) || ''
}

export function setWorkerSession(
  token: string,
  expiresAt: string,
  worker?: { workerId: number; username: string; status: string },
) {
  localStorage.setItem(WORKER_TOKEN_KEY, token)
  localStorage.setItem(WORKER_EXPIRES_AT_KEY, expiresAt)

  if (worker?.workerId) {
    localStorage.setItem(WORKER_ID_KEY, String(worker.workerId))
  }
  if (worker?.username) {
    localStorage.setItem(WORKER_USERNAME_KEY, worker.username)
  }
  if (worker?.status) {
    localStorage.setItem(WORKER_STATUS_KEY, worker.status)
  }
}

export function clearWorkerSession() {
  localStorage.removeItem(WORKER_TOKEN_KEY)
  localStorage.removeItem(WORKER_EXPIRES_AT_KEY)
  localStorage.removeItem(WORKER_ID_KEY)
  localStorage.removeItem(WORKER_USERNAME_KEY)
  localStorage.removeItem(WORKER_STATUS_KEY)
}

export function hasWorkerSession() {
  const token = getWorkerToken()
  const expiresAt = getWorkerTokenExpiresAt()
  if (!token) return false
  if (isExpired(expiresAt)) {
    clearWorkerSession()
    return false
  }
  return true
}

function isExpired(expiresAt: string) {
  if (!expiresAt) return false
  const expiresAtMs = Date.parse(expiresAt)
  return Number.isFinite(expiresAtMs) && expiresAtMs <= Date.now()
}
