const ADMIN_TOKEN_KEY = 'order-site-admin-token'
const ADMIN_EXPIRES_AT_KEY = 'order-site-admin-token-expires-at'
const ADMIN_USER_ID_KEY = 'order-site-admin-user-id'
const ADMIN_USERNAME_KEY = 'order-site-admin-username'
const ADMIN_ROLE_KEY = 'order-site-admin-role'
const ADMIN_PERMISSIONS_KEY = 'order-site-admin-permissions'

const ADMIN_ROLE_LEVEL: Record<'support' | 'operator' | 'admin' | 'finance', number> = {
  support: 1,
  operator: 2,
  admin: 3,
  finance: 0,
}

export function getAdminToken() {
  return localStorage.getItem(ADMIN_TOKEN_KEY) || ''
}

export function getAdminTokenExpiresAt() {
  return localStorage.getItem(ADMIN_EXPIRES_AT_KEY) || ''
}

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

export function getAdminUsername() {
  return localStorage.getItem(ADMIN_USERNAME_KEY) || ''
}

export function getAdminRole() {
  const role = localStorage.getItem(ADMIN_ROLE_KEY)
  if (role === 'admin' || role === 'operator' || role === 'support' || role === 'finance') {
    return role
  }

  return 'support'
}

export function getAdminPermissions(): string[] {
  try {
    const value = JSON.parse(localStorage.getItem(ADMIN_PERMISSIONS_KEY) || '[]')
    return Array.isArray(value)
      ? value.map((item) => String(item || '').trim()).filter(Boolean)
      : []
  } catch {
    return []
  }
}

export function setAdminPermissions(permissions: string[]) {
  localStorage.setItem(ADMIN_PERMISSIONS_KEY, JSON.stringify(permissions || []))
}

export function hasAdminPermission(permission: string) {
  if (!hasAdminSession()) return false
  return getAdminPermissions().includes(String(permission || '').trim())
}

export function hasAdminRole(role: 'admin' | 'operator' | 'support' | 'finance') {
  if (!hasAdminSession()) {
    return false
  }

  const currentRole = getAdminRole()
  if (role === 'finance') return currentRole === 'finance'
  if (currentRole === 'finance') return false
  return ADMIN_ROLE_LEVEL[currentRole] >= ADMIN_ROLE_LEVEL[role]
}

export function setAdminSession(
  token: string,
  expiresAt: string,
  user?: {
    userId: number
    username: string
    role: 'admin' | 'operator' | 'support' | 'finance'
    permissions?: string[]
  },
) {
  localStorage.setItem(ADMIN_TOKEN_KEY, token)
  localStorage.setItem(ADMIN_EXPIRES_AT_KEY, expiresAt)

  if (user?.userId) {
    localStorage.setItem(ADMIN_USER_ID_KEY, String(user.userId))
  }

  if (user?.username) {
    localStorage.setItem(ADMIN_USERNAME_KEY, user.username)
  }

  if (user?.role) {
    localStorage.setItem(ADMIN_ROLE_KEY, user.role)
  }

  localStorage.setItem(ADMIN_PERMISSIONS_KEY, JSON.stringify(user?.permissions || []))
}

export function clearAdminSession() {
  localStorage.removeItem(ADMIN_TOKEN_KEY)
  localStorage.removeItem(ADMIN_EXPIRES_AT_KEY)
  localStorage.removeItem(ADMIN_USER_ID_KEY)
  localStorage.removeItem(ADMIN_USERNAME_KEY)
  localStorage.removeItem(ADMIN_ROLE_KEY)
  localStorage.removeItem(ADMIN_PERMISSIONS_KEY)
}

export function hasAdminSession() {
  const token = getAdminToken()
  const expiresAt = getAdminTokenExpiresAt()

  if (!token) {
    return false
  }

  if (isExpired(expiresAt)) {
    clearAdminSession()
    return false
  }

  return true
}

function isExpired(expiresAt: string) {
  if (!expiresAt) {
    return false
  }

  const expiresAtMs = Date.parse(expiresAt)
  return Number.isFinite(expiresAtMs) && expiresAtMs <= Date.now()
}
