import { test } from 'node:test'
import assert from 'node:assert/strict'

import { parseJsonSetting } from '../src/lib/settingsJson.js'

// The client counterpart to the server's parseJsonSetting. The property that
// matters is the fail-safe one: anything unusable reads as **absent**, so the
// consumer falls back to its coded default rather than rendering an error or a
// half-applied object (THEMING_AND_NAV.md §4.4).

test('absent, empty and malformed values read as absent', () => {
  for (const bad of [undefined, null, '', '{', 'not json', 4, {}, []]) {
    assert.equal(parseJsonSetting(bad), null, `${JSON.stringify(bad)} should read as absent`)
  }
})

test('valid JSON that is not a plain object reads as absent', () => {
  // A stored `null`, number, string or array is as unusable to every consumer of
  // these keys as a syntax error is.
  for (const bad of ['null', '4', '"x"', '[]', '[{"to":"/"}]', 'true']) {
    assert.equal(parseJsonSetting(bad), null, `${bad} should read as absent`)
  }
})

test('a well-formed object is returned as parsed', () => {
  assert.deepEqual(parseJsonSetting('{"/site/news":{"order":2}}'), { '/site/news': { order: 2 } })
  assert.deepEqual(parseJsonSetting('{}'), {})
})
