import {
  normalizeKuaishouCloudFlow,
  prepareKuaishouCloudFulfillmentTask,
  probeKuaishouCloudTaskBindUrl,
  refreshKuaishouCloudTaskRoleInfo,
} from '../fulfillment/kuaishou-cloud-task-service.js'

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

  if (!flow.binding.vnId || !flow.binding.vnKey || !flow.binding.vnPhone) {
    if (flow.ticket.status === 'verified' && flow.binding.prepareStatus !== 'ready') {
      try {
        const prepared = await prepareKuaishouCloudFulfillmentTask(task, {
          source: 'claim_page_retry_binding_prepare',
          actor: { source: 'system' },
        })
        return prepared.task
      } catch {
        return task
      }
    }

    return task
  }

  try {
    const probed = await probeKuaishouCloudTaskBindUrl(task, {
      source: 'claim_page_polling_bind_url_probe',
      actor: { source: 'system' },
    })
    task = probed.task

    const result = await refreshKuaishouCloudTaskRoleInfo(task, {
      source: 'claim_page_polling',
      actor: { source: 'system' },
      recordEvent: false,
    })
    return result.task
  } catch {
    return task
  }
}

function parseTaskContext(task) {
  const rawValue = task?.context_json

  if (!rawValue) {
    return {}
  }

  if (typeof rawValue === 'object') {
    return rawValue
  }

  try {
    return JSON.parse(String(rawValue || '{}'))
  } catch {
    return {}
  }
}
