import {
  prepareFulfillmentBinding,
  refreshFulfillmentRole,
} from '../fulfillment/executors/registry.js'
import {
  isKuaishouCloudBindingMutationFrozen,
  normalizeKuaishouCloudFlow,
} from '../fulfillment/kuaishou-cloud/index.js'
import type { TaskRow } from '../../types/repository/rows.js'
import { parseTaskContext as parseTaskContextValue } from '../../utils/task-json.js'

export async function syncKuaishouCloudRoleInfo(task: TaskRow) {
  const flow = normalizeKuaishouCloudFlow(parseTaskContext(task).kuaishouCloudFulfillment)

  // 已发货/兑换中：禁止 claim 轮询换号或覆盖角色（脏单 status 可能已回退 waiting_binding）
  if (isKuaishouCloudBindingMutationFrozen(task, flow)) {
    return task
  }

  if (!flow.binding.vnId || !flow.binding.vnKey || !flow.binding.vnPhone) {
    // ticket verified 或绑定尚未 ready：补 prepare（覆盖提前核销后未取号场景）
    if (
      flow.ticket.status === 'verified' ||
      flow.binding.prepareStatus !== 'ready' ||
      !flow.binding.bindUrl
    ) {
      try {
        const prepared = await prepareFulfillmentBinding(task, {
          source: 'claim_page_retry_binding_prepare',
          actor: { source: 'system' },
        })
        return prepared?.task || task
      } catch {
        return task
      }
    }

    return task
  }

  try {
    // 只走 refresh：内部会按间隔 probe 绑链，必要时再查 bind_info
    // 不再 forceProbe + 前置 probe，避免同轮重复打上游
    const result = await refreshFulfillmentRole(task, {
      source: 'claim_page_polling',
      actor: { source: 'system' },
      recordEvent: false,
      forceProbe: false,
    })
    return result?.task || task
  } catch {
    return task
  }
}

function parseTaskContext(task: Partial<TaskRow> | null | undefined) {
  return parseTaskContextValue(task)
}
