import { buildClaimUrl } from '../../claim/claim-service.js'
import { shouldEnsureKuaishouCloudClaimLink, TASK_STATUS } from '../../../domain/task-status.js'
import {
  confirmKuaishouCloudTaskRole,
  dispatchKuaishouCloudFulfillmentTask,
  ensureTaskClaimLink,
  prepareKuaishouCloudFulfillmentTask,
  rebindKuaishouCloudTaskRole,
  redeemKuaishouCloudTask,
  refreshKuaishouCloudTaskRoleInfo,
  returnKuaishouCloudFulfillmentTask,
} from '../kuaishou-cloud/index.js'
import {
  FULFILLMENT_EXECUTOR_KEYS,
  type FulfillmentActionOptions,
  type FulfillmentActionResult,
  type FulfillmentDeliveryLink,
  type FulfillmentExecutor,
  type FulfillmentPrepareDeps,
} from './types.js'
import type { TaskRow } from '../../../types/repository/rows.js'

export const kuaishouCloudExecutor: FulfillmentExecutor = {
  key: FULFILLMENT_EXECUTOR_KEYS.KUAISHOU_CLOUD,
  preparePaidTask,
  resolveDeliveryLink,
  prepareBinding,
  rebindRole,
  refreshRole,
  confirmRole,
  redeemTask,
  dispatchTask,
  returnNumber,
}

async function preparePaidTask(
  task: TaskRow,
  deps: FulfillmentPrepareDeps,
): Promise<TaskRow | null> {
  const now = deps.nowIso()

  if (shouldEnsureKuaishouCloudClaimLink(task.task_status)) {
    if (!task.primary_claim_token_id && !String(task.claim_token || '').trim()) {
      const claimToken = await deps.createTaskClaimToken(task.id)
      return deps.updateTask(task.id, {
        claim_token: claimToken.token,
        claim_expires_at: claimToken.expired_at,
        user_action_status: 'pending_claim',
        updated_at: now,
      })
    }

    return task
  }

  const claimToken = await deps.createTaskClaimToken(task.id)

  return deps.updateTask(task.id, {
    task_status: TASK_STATUS.PENDING_BINDING_PREPARE,
    claim_token: claimToken.token,
    claim_expires_at: claimToken.expired_at,
    user_action_status: 'pending_claim',
    last_error: task.last_error || '领取链接已生成，等待电子凭证流程推进',
    updated_at: now,
  })
}

async function resolveDeliveryLink(task: TaskRow): Promise<FulfillmentDeliveryLink | null> {
  const primaryToken = String(task.primary_claim_token || task.claim_token || '').trim()
  const expireTime = task.primary_claim_expires_at || task.claim_expires_at || ''

  if (primaryToken) {
    return {
      claimUrl: buildClaimUrl(primaryToken),
      expireTime,
    }
  }

  try {
    const ensured = await ensureTaskClaimLink(task)
    return {
      claimUrl: String(ensured.claimUrl || '').trim(),
      expireTime: ensured.expiredAt || expireTime,
    }
  } catch {
    return null
  }
}

async function prepareBinding(
  task: TaskRow,
  options: FulfillmentActionOptions = {},
): Promise<FulfillmentActionResult> {
  // 后台/显式 force：旧号可被 CT 回收，忽略退号失败并取新号+新绑链
  const force = options.force === true || String(options.source || '').includes('admin_')
  const result = await prepareKuaishouCloudFulfillmentTask(task, {
    source: options.source || 'executor_prepare_binding',
    actor: options.actor,
    force,
  })
  return {
    task: result.task || task,
    claimUrl: result.claimUrl,
    token: result.token,
    flow: result.flow,
    previousVnRelease: (result as { previousVnRelease?: string }).previousVnRelease,
  }
}

async function rebindRole(
  task: TaskRow,
  options: FulfillmentActionOptions = {},
): Promise<FulfillmentActionResult> {
  const result = await rebindKuaishouCloudTaskRole(task, {
    source: options.source || 'executor_rebind_role',
    actor: options.actor,
  })
  return {
    task: result.task || task,
    claimUrl: result.claimUrl,
    token: result.token,
  }
}

async function refreshRole(
  task: TaskRow,
  options: FulfillmentActionOptions = {},
): Promise<FulfillmentActionResult> {
  const result = await refreshKuaishouCloudTaskRoleInfo(task, {
    source: options.source || 'executor_refresh_role',
    actor: options.actor,
    recordEvent: options.recordEvent !== false,
    forceProbe: options.forceProbe === true,
  })
  return {
    task: result.task || task,
    roleInfo: result.roleInfo,
  }
}

async function confirmRole(
  task: TaskRow,
  options: FulfillmentActionOptions = {},
): Promise<FulfillmentActionResult> {
  const result = await confirmKuaishouCloudTaskRole(task, {
    source: options.source || 'executor_confirm_role',
    actor: options.actor,
    errorCodePrefix: options.errorCodePrefix,
    forceProbe: options.forceProbe !== false,
  })
  return {
    task: result.task,
    alreadySettled: result.alreadySettled,
  }
}

async function redeemTask(
  task: TaskRow,
  options: FulfillmentActionOptions = {},
): Promise<FulfillmentActionResult> {
  const result = await redeemKuaishouCloudTask(task, {
    source: options.source || 'executor_redeem',
    actor: options.actor,
    autoFinalize: options.autoFinalize !== false,
    errorCodePrefix: options.errorCodePrefix,
  })
  return {
    task: result.task,
    alreadySettled: result.alreadySettled,
    concurrentSkipped: result.concurrentSkipped,
  }
}

async function dispatchTask(
  task: TaskRow,
  options: FulfillmentActionOptions = {},
): Promise<FulfillmentActionResult> {
  const result = await dispatchKuaishouCloudFulfillmentTask(task, {
    source: options.source || 'executor_dispatch',
    actor: options.actor,
    autoFinalize: options.autoFinalize === true,
  })
  return {
    task: result.task || task,
    flow: result.flow,
  }
}

async function returnNumber(
  task: TaskRow,
  options: FulfillmentActionOptions = {},
): Promise<FulfillmentActionResult> {
  const result = await returnKuaishouCloudFulfillmentTask(task, {
    source: options.source || 'executor_return_number',
    actor: options.actor,
    // 未显式传入时保持默认 true（发货收尾）；admin 清理会传 false
    consumeIndustryVoucher: options.consumeIndustryVoucher,
  })
  return {
    task: result.task || task,
    flow: result.flow,
  }
}
