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

import {
  resolveApprovalTaskRetryKey
} from '../src/views/scripts/approvalTaskRetry.js'
import {
  appendApprovalTaskRouteQuery,
  readApprovalTaskRouteState
} from '../src/views/scripts/approvalTaskRouteState.js'

test('approval retry key is stable only while the idempotent payload stays identical', () => {
  const first = resolveApprovalTaskRetryKey({
    action: 'approve',
    scopeId: 'task-1',
    payload: { reason: '核对通过', expectedTaskVersion: 3 }
  })
  const samePayload = resolveApprovalTaskRetryKey({
    action: 'approve',
    scopeId: 'task-1',
    payload: { expectedTaskVersion: 3, reason: '核对通过' },
    previousFingerprint: first.fingerprint,
    previousRequestId: first.requestId
  })
  const editedPayload = resolveApprovalTaskRetryKey({
    action: 'approve',
    scopeId: 'task-1',
    payload: { expectedTaskVersion: 3, reason: '补充核对后通过' },
    previousFingerprint: first.fingerprint,
    previousRequestId: first.requestId
  })

  assert.equal(samePayload.requestId, first.requestId)
  assert.notEqual(editedPayload.requestId, first.requestId)
})

test('approval task route state restores only supported filters and compact defaults', () => {
  const state = readApprovalTaskRouteState({
    dc_review_page: '3',
    dc_review_page_size: '10',
    dc_review_q: '  REIM-100  ',
    dc_review_risk: 'high',
    dc_review_sla: 'overdue'
  })
  assert.deepEqual(state, {
    page: 3,
    pageSize: 10,
    filters: { keyword: 'REIM-100', riskLevel: 'high', slaState: 'overdue' }
  })
  assert.deepEqual(appendApprovalTaskRouteQuery({}, state), {
    dc_review_page: '3',
    dc_review_page_size: '10',
    dc_review_q: 'REIM-100',
    dc_review_risk: 'high',
    dc_review_sla: 'overdue'
  })
  assert.deepEqual(readApprovalTaskRouteState({
    dc_review_page: '-1',
    dc_review_page_size: '200',
    dc_review_risk: 'unknown',
    dc_review_sla: 'near_due'
  }), {
    page: 1,
    pageSize: 20,
    filters: { keyword: '', riskLevel: '', slaState: '' }
  })
})
