export function pickFirstNonEmpty(values: unknown[]) {
  for (const value of values) {
    const normalized = String(value || '').trim()
    if (normalized) {
      return normalized
    }
  }

  return ''
}

export function isPlainObject(value: unknown): value is JsonObject {
  return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
}

import { getCloudtentaclesSourceByKey } from '../../../platforms/cloudtentacles/source-config-service.js'
import { getCloudtentaclesSessionStateByKey } from '../../../platforms/cloudtentacles/session-state-service.js'
import type { JsonObject } from '../../../../types/json.js'
import {
  normalizeCloudtentaclesDeviceId,
  normalizeCloudtentaclesDeviceType,
} from '../../../platforms/cloudtentacles/defaults.js'

export function resolveCloudtentaclesAdminContext(
  payload: JsonObject = {},
  options: JsonObject = {},
) {
  const sourceKey = String(payload.sourceKey || options.sourceKey || 'default').trim()
  const savedSource = options.savedSource || getCloudtentaclesSourceByKey(sourceKey) || {}
  const persistedSession =
    options.persistedSession || getCloudtentaclesSessionStateByKey(sourceKey) || {}
  const defaultBaseUrl = String(options.defaultBaseUrl || 'https://123.207.217.176').trim()
  return {
    sourceKey,
    baseUrl: pickFirstNonEmpty([payload.baseUrl, savedSource.baseUrl, defaultBaseUrl]),
    token: pickFirstNonEmpty([payload.token, persistedSession.token]),
    deviceId: normalizeCloudtentaclesDeviceId(
      pickFirstNonEmpty([payload.deviceId, savedSource.deviceId, persistedSession.deviceId]),
    ),
    deviceType: normalizeCloudtentaclesDeviceType(
      payload.deviceType ?? savedSource.deviceType ?? persistedSession.deviceType,
    ),
  }
}

export function hasCloudtentaclesCredentialContextChanged(
  current: JsonObject = {},
  next: JsonObject = {},
) {
  return (
    String(current.baseUrl || '').trim() !== String(next.baseUrl || '').trim() ||
    String(current.username || '').trim() !== String(next.username || '').trim() ||
    String(current.phone || '').trim() !== String(next.phone || '').trim() ||
    String(current.deviceId || '').trim() !== String(next.deviceId || '').trim() ||
    Number(current.deviceType || 0) !== Number(next.deviceType || 0)
  )
}
