import { updateTask } from '../../../repositories/task-repo.js'
import { probeCloudtentaclesBindUrl } from '../../platforms/cloudtentacles/virtual-number-service.js'
import { resolveCloudtentaclesConfig } from '../../platforms/cloudtentacles/helpers.js'
import { createHttpError } from '../../../utils/http.js'
import { nowIso } from '../../../utils/time.js'
import {
  isKuaishouCloudBindUrlFresh,
  isKuaishouCloudBindingMutationFrozen,
  isKuaishouCloudTask,
  normalizeKuaishouCloudFlow,
  normalizeKuaishouCloudRoleInfo,
  type JsonObject,
} from './domain.js'
import { parseTaskContext } from './task-context.js'
import { buildRoleStateFromCurrentInfo } from './role-state.js'
import { refreshKuaishouCloudTaskBindUrl } from './prepare-fulfillment.js'
import type { TaskRow } from '../../../types/repository/rows.js'

export async function probeKuaishouCloudTaskBindUrl(task: TaskRow, options: JsonObject = {}) {
  if (!isKuaishouCloudTask(task)) {
    throw createHttpError('当前任务不是 kuaishou-lewan 履约任务', {
      statusCode: 409,
      errorCode: 'kuaishou_cloud_task_invalid',
    })
  }

  const now = nowIso()
  const taskContext = parseTaskContext(task)
  const flow = normalizeKuaishouCloudFlow(taskContext.kuaishouCloudFulfillment)

  // 已发货：禁止 probe 触发过期换号 / 覆盖角色
  if (isKuaishouCloudBindingMutationFrozen(task, flow)) {
    return {
      task,
      flow,
      probe: null as null,
    }
  }

  if (!flow.binding.bindUrl) {
    return {
      task,
      flow,
      probe: null as null,
    }
  }

  const probeIntervalMs =
    Number(resolveCloudtentaclesConfig().bindUrlProbeIntervalSeconds || 30) * 1000
  const lastProbeAt = flow.binding.bindProbeAt ? Date.parse(String(flow.binding.bindProbeAt)) : NaN
  if (
    !options.force &&
    Number.isFinite(lastProbeAt) &&
    Date.now() - lastProbeAt < probeIntervalMs
  ) {
    return {
      task,
      flow,
      probe: null as null,
    }
  }

  const probe = await probeCloudtentaclesBindUrl({
    bindUrl: flow.binding.bindUrl,
  })

  if (probe.expired || !isKuaishouCloudBindUrlFresh(flow)) {
    const refreshed = await refreshKuaishouCloudTaskBindUrl(task, {
      source: options.source || 'claim_page_bind_url_expired',
      actor: options.actor || { source: 'system' },
    })
    return {
      ...refreshed,
      probe,
    }
  }

  const probeRoleInfo = normalizeKuaishouCloudRoleInfo(probe.roleInfo)
  const hasRoleInfo = Boolean(probeRoleInfo.name || probeRoleInfo.rid)
  const roleState = hasRoleInfo
    ? buildRoleStateFromCurrentInfo({
        flow,
        roleInfo: probeRoleInfo,
        now,
        emptyMessage: '当前还没有查询到角色信息，请完成绑定后稍等片刻再试',
      })
    : null
  const nextContext = {
    ...taskContext,
    kuaishouCloudFulfillment: {
      ...flow,
      binding: {
        ...flow.binding,
        bindProbeAt: now,
        bindProbeStatus: probe.valid ? 'valid' : 'invalid',
        bindProbeMessage: String(probe.message || probe.reason || '').trim(),
        roleName: roleState ? roleState.bindingRoleName : flow.binding.roleName,
        roleId: roleState ? roleState.bindingRoleId : flow.binding.roleId,
      },
      role: roleState ? roleState.role : flow.role,
    },
  }

  const updatedTask = await updateTask(task.id, {
    role_id: roleState && !roleState.isDefaultRole ? probeRoleInfo.rid : task.role_id,
    role_name: roleState && !roleState.isDefaultRole ? probeRoleInfo.name : task.role_name,
    context_json: JSON.stringify(nextContext),
    updated_at: now,
  })

  return {
    task: updatedTask,
    flow: normalizeKuaishouCloudFlow(nextContext.kuaishouCloudFulfillment),
    probe,
  }
}
