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

import { buildClaimUrl } from '../claim/claim-service.js'
import { resolveTaskDeliveryLink } from './delivery-link-service.js'
import type { TaskRow } from '../../types/repository/rows.js'

test('resolveTaskDeliveryLink 为 cloud 任务返回内部领取链接', async () => {
  const result = await resolveTaskDeliveryLink(
    createTask({
      executor_key: 'kuaishou_ct_assisted',
      primary_claim_token: 'cloud-token',
      primary_claim_expires_at: '2026-07-09T00:00:00.000Z',
    }),
  )

  assert.deepEqual(result, {
    claimUrl: buildClaimUrl('cloud-token'),
    expireTime: '2026-07-09T00:00:00.000Z',
  })
})

test('resolveTaskDeliveryLink 兼容历史 kuaishou-industry cloud 任务', async () => {
  const result = await resolveTaskDeliveryLink(
    createTask({
      executor_key: 'kuaishou-industry',
      claim_token: 'industry-token',
      claim_expires_at: '2026-07-09T08:00:00.000Z',
    }),
  )

  assert.deepEqual(result, {
    claimUrl: buildClaimUrl('industry-token'),
    expireTime: '2026-07-09T08:00:00.000Z',
  })
})

test('resolveTaskDeliveryLink 为 feifei 任务返回本站领取链接', async () => {
  const result = await resolveTaskDeliveryLink(
    createTask({
      executor_key: 'kuaishou_feifei',
      primary_claim_token: 'feifei-token',
      primary_claim_expires_at: '2026-07-09T12:00:00.000Z',
      context_json: {
        kuaishouFeifei: {
          h5: {
            rechargeUrl: 'https://feifei.example.com/h5/bind?code=very-long',
          },
        },
      },
    }),
  )

  assert.deepEqual(result, {
    claimUrl: buildClaimUrl('feifei-token'),
    expireTime: '2026-07-09T12:00:00.000Z',
  })
})

test('resolveTaskDeliveryLink 对人工履约任务返回 null', async () => {
  const result = await resolveTaskDeliveryLink(
    createTask({
      executor_key: 'manual_dispatch',
    }),
  )

  assert.equal(result, null)
})

function createTask(patch: Partial<TaskRow> = {}): TaskRow {
  return {
    id: 123,
    order_id: 456,
    order_item_id: 789,
    unit_index: 1,
    platform_order_id: '2614900602069169',
    profile_id: 0,
    task_no: 'DT-test',
    executor_key: 'kuaishou_ct_assisted',
    task_status: 'pending_binding_prepare',
    delivery_status: 'pending',
    result_code: '',
    result_message: '',
    automation_mode: 'manual',
    requires_claim: true,
    user_action_status: 'pending_claim',
    attempt_count: 0,
    runtime_session_id: '',
    login_type: '',
    nickname: '',
    role_name: '',
    role_id: '',
    area: '',
    partition_name: '',
    claim_token: '',
    primary_claim_token: '',
    primary_claim_token_id: null,
    primary_claim_token_status: '',
    artifacts_json: '{}',
    context_json: '{}',
    screenshot_path: '',
    last_error: '',
    retry_count: 0,
    created_at: '2026-07-08T00:00:00.000Z',
    updated_at: '2026-07-08T00:00:00.000Z',
    claimed_at: null,
    role_confirmed_at: null,
    redeemed_at: null,
    ...patch,
  }
}
