import { TASK_STATUS } from '../../../domain/task-status.js'
import {
  FULFILLMENT_EXECUTOR_KEYS,
  type FulfillmentExecutor,
  type FulfillmentPrepareDeps,
} from './types.js'
import type { TaskRow } from '../../../types/repository/rows.js'

export const manualDispatchExecutor: FulfillmentExecutor = {
  key: FULFILLMENT_EXECUTOR_KEYS.MANUAL_DISPATCH,
  preparePaidTask,
}

async function preparePaidTask(
  task: TaskRow,
  deps: FulfillmentPrepareDeps,
): Promise<TaskRow | null> {
  const lastError = task.last_error || '当前任务需要人工履约处理'
  const updatedTask = await deps.updateTask(task.id, {
    task_status: TASK_STATUS.MANUAL_REVIEW,
    user_action_status: 'not_required',
    last_error: lastError,
    updated_at: deps.nowIso(),
  })

  await deps.notifyTaskAutoManualReview({
    task: updatedTask || task,
    reason: lastError,
    source: 'manual_dispatch_profile',
  })

  return updatedTask
}
