import { buildClaimUrl } from '../../claim/claim-service.js'
import { TASK_STATUS } from '../../../domain/task-status.js'
import { prepareKuaishouFeifeiTask } from '../kuaishou-feifei/index.js'
import {
  FULFILLMENT_EXECUTOR_KEYS,
  type FulfillmentDeliveryLink,
  type FulfillmentExecutor,
  type FulfillmentPrepareDeps,
} from './types.js'
import type { TaskRow } from '../../../types/repository/rows.js'

export const kuaishouFeifeiExecutor: FulfillmentExecutor = {
  key: FULFILLMENT_EXECUTOR_KEYS.KUAISHOU_FEIFEI,
  preparePaidTask,
  resolveDeliveryLink,
}

async function preparePaidTask(
  task: TaskRow,
  deps: FulfillmentPrepareDeps,
): Promise<TaskRow | null> {
  try {
    let workingTask = task
    if (!task.primary_claim_token_id && !String(task.claim_token || '').trim()) {
      const claimToken = await deps.createTaskClaimToken(task.id)
      workingTask =
        (await deps.updateTask(task.id, {
          claim_token: claimToken.token,
          claim_expires_at: claimToken.expired_at,
          user_action_status: 'pending_claim',
          updated_at: deps.nowIso(),
        })) || task
    }

    return await prepareKuaishouFeifeiTask(workingTask)
  } catch (error) {
    const message = error instanceof Error ? error.message : 'kuaishou-feifei 订单创建失败'
    const updatedTask = await deps.updateTask(task.id, {
      task_status: TASK_STATUS.MANUAL_REVIEW,
      user_action_status: 'not_required',
      last_error: message,
      result_code: 'kuaishou_feifei_prepare_failed',
      result_message: message,
      updated_at: deps.nowIso(),
    })
    await deps.notifyTaskAutoManualReview({
      task: updatedTask || task,
      reason: message,
      source: 'kuaishou_feifei_prepare_failed',
    })
    return updatedTask
  }
}

/**
 * 对外（91 等）统一返回本站领取链接，不再返回 feifei H5 或短链。
 */
async function resolveDeliveryLink(task: TaskRow): Promise<FulfillmentDeliveryLink | null> {
  const primaryToken = String(task.primary_claim_token || task.claim_token || '').trim()
  const expireTime = String(task.primary_claim_expires_at || task.claim_expires_at || '').trim()

  if (!primaryToken) {
    return null
  }

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