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

import {
  hasCloudtentaclesCredentialContextChanged,
  isPlainObject,
  pickFirstNonEmpty,
  resolveCloudtentaclesAdminContext,
} from './context.js'

test('pickFirstNonEmpty returns first trimmed non-empty string value', () => {
  assert.equal(pickFirstNonEmpty(['', '  ', ' value ', 'fallback']), 'value')
  assert.equal(pickFirstNonEmpty([null, undefined, 0, '']), '')
})

test('isPlainObject only accepts non-array objects', () => {
  assert.equal(isPlainObject({ a: 1 }), true)
  assert.equal(isPlainObject([]), false)
  assert.equal(isPlainObject(null), false)
  assert.equal(isPlainObject('x'), false)
})

test('resolveCloudtentaclesAdminContext merges payload source and persisted session', () => {
  const context = resolveCloudtentaclesAdminContext(
    {
      token: ' token-1 ',
      deviceType: 3,
    },
    {
      savedSource: {
        baseUrl: ' https://saved.example.com ',
        deviceId: ' device-saved ',
        deviceType: 1,
      },
      persistedSession: {
        token: 'token-persisted',
        deviceId: 'device-persisted',
        deviceType: 2,
      },
    },
  )

  assert.deepEqual(context, {
    sourceKey: 'default',
    baseUrl: 'https://saved.example.com',
    token: 'token-1',
    deviceId: 'device-saved',
    deviceType: 3,
  })
})

test('hasCloudtentaclesCredentialContextChanged detects normalized credential changes', () => {
  assert.equal(
    hasCloudtentaclesCredentialContextChanged(
      {
        baseUrl: ' https://a ',
        username: 'u1',
        phone: '13812345678',
        deviceId: 'd1',
        deviceType: 1,
      },
      { baseUrl: 'https://a', username: 'u1', phone: '13812345678', deviceId: 'd1', deviceType: 1 },
    ),
    false,
  )

  assert.equal(
    hasCloudtentaclesCredentialContextChanged(
      { baseUrl: 'https://a', username: 'u1', phone: '13812345678', deviceId: 'd1', deviceType: 1 },
      { baseUrl: 'https://b', username: 'u1', phone: '13812345678', deviceId: 'd1', deviceType: 1 },
    ),
    true,
  )
})
