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

import {
  canViewerCloseTask,
  createAdminViewerContext,
  mapKuaishouCloudFulfillmentContext,
  resolveAdminTaskScreenshotUrl,
} from './admin-read-shared-helpers.js'

test('resolveAdminTaskScreenshotUrl lets support view final redeemed screenshot', async () => {
  const task = {
    id: 12,
    screenshot_path: '/tmp/redeemed-12.png',
    runtime_session_id: '',
  }

  const screenshotUrl = await resolveAdminTaskScreenshotUrl(
    task,
    createAdminViewerContext({ role: 'support' }),
  )

  assert.equal(screenshotUrl, '/api/v1/admin/tasks/12/screenshot')
})

test('resolveAdminTaskScreenshotUrl falls back to review screenshot when runtime session exists', async () => {
  const task = {
    id: 13,
    screenshot_path: '',
    runtime_session_id: 'runtime-session-13',
  }

  const screenshotUrl = await resolveAdminTaskScreenshotUrl(
    task,
    createAdminViewerContext({ role: 'support' }),
  )

  assert.equal(screenshotUrl, '/api/v1/admin/tasks/13/screenshot')
})

test('canViewerCloseTask allows support to close active task but not redeemed task', () => {
  const viewerContext = createAdminViewerContext({ role: 'support' })

  assert.equal(canViewerCloseTask({ task_status: 'link_generated' }, viewerContext), true)
  assert.equal(canViewerCloseTask({ task_status: 'redeemed' }, viewerContext), false)
})

test('createAdminViewerContext lets support operate vouchers without lifecycle permissions', () => {
  const viewerContext = createAdminViewerContext({ role: 'support' })

  assert.equal(viewerContext.canOperateKuaishouIndustryVoucher, true)
  assert.equal(viewerContext.canOperateAssistedTask, true)
  assert.equal(viewerContext.canManageTaskLifecycle, false)
})

test('createAdminViewerContext lets support rebind-assisted actions without full lifecycle', () => {
  const support = createAdminViewerContext({ role: 'support' })
  const operator = createAdminViewerContext({ role: 'operator' })

  // 客服：可协助换绑/刷新角色，不可管理任务生命周期（重试/发货/退号等）
  assert.equal(support.canOperateAssistedTask, true)
  assert.equal(support.canManageTaskLifecycle, false)

  // 运营：两者皆可
  assert.equal(operator.canOperateAssistedTask, true)
  assert.equal(operator.canManageTaskLifecycle, true)
})

test('mapKuaishouCloudFulfillmentContext exposes cloud account display labels', () => {
  const flow = mapKuaishouCloudFulfillmentContext(
    {
      binding: {
        cloudSourceKeys: [' account_a ', 'account_b'],
        resolvedSourceKey: 'account_b',
      },
    },
    {
      cloudSourceLabelMap: new Map([
        ['account_a', '白班账号'],
        ['account_b', '夜班账号'],
      ]),
    },
  )

  assert.deepEqual(flow?.binding.cloudSourceKeys, ['account_a', 'account_b'])
  assert.deepEqual(flow?.binding.cloudSourceLabels, ['白班账号', '夜班账号'])
  assert.equal(flow?.binding.resolvedSourceLabel, '夜班账号')
})
