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

import { buildAffiliateDashClientOrderNo } from './index.js'
import type { TaskRow } from '../../../types/repository/rows.js'

function buildTask(overrides: Partial<TaskRow> = {}): TaskRow {
  return {
    id: 101,
    order_id: 10,
    order_item_id: 20,
    unit_index: 1,
    platform_order_id: '2622300001260431',
    profile_id: 1,
    task_no: 'DTeb37abafd722',
    executor_key: 'affiliate_dash',
    task_status: 'pending_payment',
    delivery_status: 'pending',
    result_code: '',
    result_message: '',
    automation_mode: 'automatic',
    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-08-11T00:00:00.000Z',
    updated_at: '2026-08-11T00:00:00.000Z',
    claimed_at: null,
    role_confirmed_at: null,
    redeemed_at: null,
    ...overrides,
  }
}

test('buildAffiliateDashClientOrderNo uses the platform order number for a single task', () => {
  const task = buildTask()

  assert.equal(buildAffiliateDashClientOrderNo(task, [task]), '2622300001260431')
})

test('buildAffiliateDashClientOrderNo appends a stable position for split affiliate-dash tasks', () => {
  const firstTask = buildTask({ id: 101, unit_index: 1 })
  const secondTask = buildTask({ id: 102, order_item_id: 21, unit_index: 1 })

  assert.equal(
    buildAffiliateDashClientOrderNo(firstTask, [secondTask, firstTask]),
    '2622300001260431-1',
  )
  assert.equal(
    buildAffiliateDashClientOrderNo(secondTask, [secondTask, firstTask]),
    '2622300001260431-2',
  )
})

test('buildAffiliateDashClientOrderNo falls back to the task number without a platform order number', () => {
  const task = buildTask({ platform_order_id: '' })

  assert.equal(buildAffiliateDashClientOrderNo(task, [task]), 'DTeb37abafd722')
})
