import test from 'node:test'
import assert from 'node:assert/strict'

import { syncDeliveryTasksForOrderWithDeps } from './delivery-task-service.js'

const paidOrder = {
  id: 10,
  provider: 'agiso',
  platform: 'xianyu',
  shop_id: 'shop-1',
  shop_name: '测试店铺',
  platform_order_id: 'P10001',
  pay_status: 'paid',
}

const orderItems = [
  {
    id: 20,
    sku_code: 'dnf-cdk-a',
    sku_name: 'DNF CDK A',
    quantity: 1,
  },
]

function createTaskFixture(patch = {}) {
  return {
    id: 30,
    order_item_id: 20,
    task_status: 'paid',
    executor_key: 'tencent_claim_assisted',
    requires_claim: true,
    claim_token: '',
    primary_claim_token_id: null,
    primary_inventory_item_id: null,
    last_error: '',
    context_json: JSON.stringify({
      inventorySkuCode: 'dnf-cdk-a',
      primaryRequirement: {
        roleKey: 'primary_code',
        credentialType: 'tencent_code',
      },
    }),
    ...patch,
  }
}

test('syncDeliveryTasksForOrderWithDeps moves paid claim task to waiting inventory when reservation fails', async () => {
  const updates = []
  const reserveCalls = []

  const result = await syncDeliveryTasksForOrderWithDeps(paidOrder, orderItems, {
    listTasksByOrderId: async () => [createTaskFixture()],
    reserveInventoryForTask: async (payload) => {
      reserveCalls.push(payload)
      return null
    },
    updateTask: async (taskId, patch) => {
      updates.push({ taskId, patch })
      return { id: taskId, ...patch }
    },
    nowIso: () => '2026-04-14T12:00:00.000Z',
  })

  assert.deepEqual(reserveCalls, [
    {
      skuCode: 'dnf-cdk-a',
      taskId: 30,
      credentialType: 'tencent_code',
      roleKey: 'primary_code',
    },
  ])
  assert.deepEqual(updates, [
    {
      taskId: 30,
      patch: {
        task_status: 'waiting_inventory',
        inventory_status: 'pending',
        last_error: '库存不足，等待可用库存凭据',
        updated_at: '2026-04-14T12:00:00.000Z',
      },
    },
  ])
  assert.equal(result[0]?.task_status, 'waiting_inventory')
})

test('syncDeliveryTasksForOrderWithDeps sends manual dispatch tasks to manual review', async () => {
  const notifications = []
  const updates = []

  const result = await syncDeliveryTasksForOrderWithDeps(paidOrder, orderItems, {
    listTasksByOrderId: async () => [createTaskFixture({
      executor_key: 'manual_dispatch',
      requires_claim: false,
      context_json: '{}',
    })],
    updateTask: async (taskId, patch) => {
      updates.push({ taskId, patch })
      return { id: taskId, ...patch }
    },
    notifyTaskAutoManualReview: async (payload) => {
      notifications.push(payload)
      return { ok: true }
    },
    nowIso: () => '2026-04-14T12:01:00.000Z',
  })

  assert.equal(result[0]?.task_status, 'manual_review')
  assert.equal(updates[0]?.patch.last_error, '当前任务需要人工履约处理')
  assert.deepEqual(
    notifications.map((item) => ({
      reason: item.reason,
      source: item.source,
      taskStatus: item.task.task_status,
    })),
    [
      {
        reason: '当前任务需要人工履约处理',
        source: 'manual_dispatch_profile',
        taskStatus: 'manual_review',
      },
    ],
  )
})

test('syncDeliveryTasksForOrderWithDeps prepares kuaishou cloud task with claim token', async () => {
  const claimToken = {
    token: 'claim-token',
    expired_at: '2026-04-15T12:00:00.000Z',
  }
  const updates = []

  const result = await syncDeliveryTasksForOrderWithDeps(paidOrder, orderItems, {
    listTasksByOrderId: async () => [createTaskFixture({
      executor_key: 'kuaishou_ct_assisted',
      task_status: 'paid',
      requires_claim: true,
      context_json: '{}',
    })],
    createTaskClaimToken: async (taskId) => ({ ...claimToken, taskId }),
    updateTask: async (taskId, patch) => {
      updates.push({ taskId, patch })
      return { id: taskId, ...patch }
    },
    nowIso: () => '2026-04-14T12:02:00.000Z',
  })

  assert.equal(result[0]?.task_status, 'pending_binding_prepare')
  assert.deepEqual(updates, [
    {
      taskId: 30,
      patch: {
        task_status: 'pending_binding_prepare',
        inventory_status: 'not_required',
        claim_token: 'claim-token',
        claim_expires_at: '2026-04-15T12:00:00.000Z',
        user_action_status: 'pending_claim',
        last_error: '领取链接已生成，等待客户提交核销码',
        updated_at: '2026-04-14T12:02:00.000Z',
      },
    },
  ])
})
