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'
import { pickFirstNonEmpty, resolveCloudtentaclesAdminContext } from './context.js'
import { maskPhone, maskSecret } from './mappers.js'

const DEFAULT_CLOUDTENTACLES_BASE_URL = 'https://123.207.217.176'

function _resolveSourceKey(payload: JsonObject = {}) {
  return String(payload.sourceKey || '').trim() || 'default'
}

export function resolveAdminCloudtentaclesCredentialPayload(
  payload: JsonObject = {},
  options: JsonObject = {},
) {
  const sourceKey = _resolveSourceKey(payload)
  const savedSource = options.savedSource || getCloudtentaclesSourceByKey(sourceKey) || {}
  const defaultBaseUrl = String(options.defaultBaseUrl || DEFAULT_CLOUDTENTACLES_BASE_URL).trim()

  return {
    sourceKey,
    baseUrl: pickFirstNonEmpty([payload.baseUrl, savedSource.baseUrl, defaultBaseUrl]),
    username: pickFirstNonEmpty([payload.username, savedSource.username]),
    password: pickFirstNonEmpty([payload.password, savedSource.password]),
    phone: pickFirstNonEmpty([payload.phone, savedSource.phone]),
    deviceId: normalizeCloudtentaclesDeviceId(
      pickFirstNonEmpty([payload.deviceId, savedSource.deviceId]),
    ),
    deviceType: normalizeCloudtentaclesDeviceType(payload.deviceType ?? savedSource.deviceType),
  }
}

export function resolveAdminCloudtentaclesSessionPayload(
  payload: JsonObject = {},
  options: JsonObject = {},
) {
  const sourceKey = _resolveSourceKey(payload)
  const savedSource = options.savedSource || getCloudtentaclesSourceByKey(sourceKey) || {}
  const persistedSession =
    options.persistedSession || getCloudtentaclesSessionStateByKey(sourceKey) || {}

  return resolveCloudtentaclesAdminContext(payload, {
    savedSource,
    persistedSession,
    sourceKey,
    defaultBaseUrl: options.defaultBaseUrl || DEFAULT_CLOUDTENTACLES_BASE_URL,
  })
}

export function buildAdminCloudtentaclesPersistedSessionPayload(
  session: JsonObject = {},
  options: JsonObject = {},
) {
  return {
    token: String(session.token || '').trim(),
    baseUrl: String(session.baseUrl || '').trim(),
    username: pickFirstNonEmpty([options.username, session.username]),
    phone: pickFirstNonEmpty([options.phone, session.phone]),
    loggedInAt: String(session.loggedInAt || '').trim(),
    deviceId: normalizeCloudtentaclesDeviceId(
      pickFirstNonEmpty([options.deviceId, session.deviceId]),
    ),
    deviceType: normalizeCloudtentaclesDeviceType(options.deviceType ?? session.deviceType),
  }
}

export function buildAdminCloudtentaclesSessionSummary(
  session: JsonObject = {},
  savedSession: JsonObject = {},
  sourceKey = 'default',
) {
  const permissions = Array.isArray(session.permissions) ? session.permissions : []

  return {
    sourceKey,
    tokenMasked: maskSecret(session.token),
    permissionCount: permissions.length,
    permissions,
    persisted: Boolean(savedSession.token),
  }
}

export function buildAdminCloudtentaclesLoginResult(
  session: JsonObject = {},
  savedSession: JsonObject = {},
  sourceKey = 'default',
) {
  return {
    sourceKey,
    baseUrl: String(session.baseUrl || '').trim(),
    username: String(session.username || '').trim(),
    phoneMasked: maskPhone(session.phone),
    loggedInAt: String(session.loggedInAt || '').trim(),
    responseMessage: String(session.responseMessage || '').trim(),
    token: String(session.token || '').trim(),
    session: buildAdminCloudtentaclesSessionSummary(session, savedSession, sourceKey),
    userInfo: session.userInfo,
    asset: session.asset,
  }
}

export function buildAdminCloudtentaclesValidateResult(
  session: JsonObject = {},
  savedSession: JsonObject = {},
  sourceKey = 'default',
) {
  return {
    sourceKey,
    baseUrl: String(session.baseUrl || '').trim(),
    loggedInAt: String(session.loggedInAt || '').trim(),
    session: buildAdminCloudtentaclesSessionSummary(session, savedSession, sourceKey),
    userInfo: session.userInfo,
    asset: session.asset,
  }
}
