import { getCloudtentaclesAsset } from '../platforms/cloudtentacles/catalog-service.js'
import { getCloudtentaclesSourceConfig } from '../platforms/cloudtentacles/source-config-service.js'
import { getCloudtentaclesSessionState } from '../platforms/cloudtentacles/session-state-service.js'
import {
  notifyCloudtentaclesAssetLow,
  notifyCloudtentaclesAuthExpired,
} from '../notification/domain-notifications.js'

type JsonObject = Record<string, any>

export async function runCloudtentaclesHealthJob(job: JsonObject) {
  const source = getCloudtentaclesSourceConfig()
  const session = getCloudtentaclesSessionState()
  const token = String(session.token || '').trim()
  const threshold = Number(job.config?.assetThreshold || 500)
  const cooldownSeconds = Number(job.cooldownSeconds || 1800)

  if (!token) {
    await notifyCloudtentaclesAuthExpired({
      pathname: '/user/get_asset',
      errorCode: 'cloudtentacles_token_missing',
      message: '当前 cloudtentacles 没有可用 token，请到后台重新登录',
      cooldownSeconds,
    })

    return {
      ok: false,
      status: 'auth_missing',
      message: 'cloudtentacles token 缺失',
      asset: null,
      threshold,
    }
  }

  const assetResult = await getCloudtentaclesAsset({
    baseUrl: String(session.baseUrl || source.baseUrl || '').trim() || 'https://123.207.217.176',
    token,
    deviceId: String(session.deviceId || source.deviceId || '-').trim() || '-',
    deviceType: Number(session.deviceType ?? source.deviceType ?? 0),
  })
  const asset = Number(assetResult.asset || 0)

  if (asset < threshold) {
    await notifyCloudtentaclesAssetLow({
      asset,
      threshold,
      cooldownSeconds,
    })
  }

  return {
    ok: true,
    status: asset < threshold ? 'asset_low' : 'ok',
    message: asset < threshold ? `余额 ${asset} 低于阈值 ${threshold}` : `余额 ${asset} 正常`,
    asset,
    threshold,
  }
}
