/**
 * 角色状态与默认角色快照（诊断用）。
 * 履约主闸已改为 claimIdentity.expectedUid；默认角色不再作为 ready 硬门槛。
 */
import { getCloudtentaclesBindInfo } from '../../platforms/cloudtentacles/virtual-number-service.js'
import {
  hasKuaishouCloudDefaultRoleSnapshot,
  isSameKuaishouCloudRoleIdentity,
  normalizeKuaishouCloudRoleInfo,
  type JsonObject,
  type KuaishouCloudFlow,
} from './domain.js'

export type KuaishouCloudDefaultRoleSnapshot = {
  defaultName: string
  defaultRid: string
  defaultCapturedAt: string | null
  defaultCaptureStatus: string
  defaultErrorMessage: string
}

export async function captureKuaishouCloudDefaultRoleSnapshot({
  cloudContext,
  preparedBinding,
  now,
}: {
  cloudContext: JsonObject
  preparedBinding: JsonObject
  now: string
}): Promise<KuaishouCloudDefaultRoleSnapshot> {
  try {
    const bindInfoResult = await getCloudtentaclesBindInfo({
      ...cloudContext,
      key: preparedBinding.vnKey,
      id: preparedBinding.vnId,
    })
    const roleInfo = normalizeKuaishouCloudRoleInfo(bindInfoResult.bindInfo)
    const hasRole = Boolean(roleInfo.name || roleInfo.rid)

    return {
      defaultName: roleInfo.name,
      defaultRid: roleInfo.rid,
      defaultCapturedAt: hasRole ? now : null,
      defaultCaptureStatus: hasRole ? 'captured' : 'empty',
      defaultErrorMessage: hasRole ? '' : '未获取到虚拟机默认角色信息，请稍后刷新',
    }
  } catch (error) {
    return {
      defaultName: '',
      defaultRid: '',
      defaultCapturedAt: null,
      defaultCaptureStatus: 'failed',
      defaultErrorMessage:
        error instanceof Error ? error.message : '获取虚拟机默认角色信息失败，请稍后刷新',
    }
  }
}

export function buildPendingRoleWithDefaultSnapshot(snapshot: KuaishouCloudDefaultRoleSnapshot) {
  return {
    status: 'pending',
    name: '',
    rid: '',
    refreshedAt: null as null,
    errorMessage: snapshot.defaultErrorMessage || '',
    rawInfo: null as null,
    defaultName: snapshot.defaultName,
    defaultRid: snapshot.defaultRid,
    defaultCapturedAt: snapshot.defaultCapturedAt,
    defaultCaptureStatus: snapshot.defaultCaptureStatus,
    defaultErrorMessage: snapshot.defaultErrorMessage,
    isDefaultRole: false,
  }
}

export function buildRoleStateFromCurrentInfo({
  flow,
  roleInfo,
  now,
  emptyMessage,
}: {
  flow: KuaishouCloudFlow
  roleInfo: { name: string; rid: string; rawInfo?: unknown }
  now: string
  emptyMessage: string
}) {
  const hasRoleInfo = Boolean(roleInfo.name || roleInfo.rid)
  const hasDefaultRole = hasKuaishouCloudDefaultRoleSnapshot(flow)
  const isDefaultRole =
    hasRoleInfo &&
    hasDefaultRole &&
    isSameKuaishouCloudRoleIdentity(
      { name: roleInfo.name, rid: roleInfo.rid },
      { name: flow.role.defaultName, rid: flow.role.defaultRid },
    )

  // UID 主闸：只要有绑定角色信息就视为 ready 并落库 rid；
  // isDefaultRole 仅作诊断文案，不再清空 roleId。
  return {
    hasRoleInfo,
    isDefaultRole,
    bindingRoleName: hasRoleInfo ? roleInfo.name : '',
    bindingRoleId: hasRoleInfo ? roleInfo.rid : '',
    role: {
      ...flow.role,
      status: hasRoleInfo ? 'ready' : 'pending',
      name: hasRoleInfo ? roleInfo.name : '',
      rid: hasRoleInfo ? roleInfo.rid : '',
      refreshedAt: now,
      errorMessage: hasRoleInfo
        ? isDefaultRole
          ? '当前绑定接近虚拟机默认角色，请确认已绑定自己的角色，并与填写 UID 一致'
          : ''
        : emptyMessage,
      rawInfo: roleInfo.rawInfo || null,
      isDefaultRole,
    },
  }
}
