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

import {
  countNewDocuments,
  isNewDocument,
  markDocumentViewed,
  readDocumentScope,
  readViewedDocumentKeys,
  resolveDocumentNewKey,
  writeDocumentScope
} from '../src/utils/documentCenterNewState.js'
import { buildDocumentInboxRows } from '../src/composables/useDocumentCenterInbox.js'

function createMemoryStorage(initial = {}) {
  const store = new Map(Object.entries(initial))
  return {
    getItem(key) {
      return store.has(key) ? store.get(key) : null
    },
    setItem(key, value) {
      store.set(key, value)
    }
  }
}

test('document center new state resolves source scoped document keys', () => {
  assert.equal(resolveDocumentNewKey({ source: 'archive', claimId: 'claim-1' }), 'archive:claim-1')
  assert.equal(resolveDocumentNewKey({ source: 'approval', documentNo: 'EXP-1' }), 'approval:EXP-1')
})

test('document center new state counts unseen documents and persists viewed rows', () => {
  const storage = createMemoryStorage()
  const rows = [
    { source: 'archive', claimId: 'claim-1' },
    { source: 'archive', claimId: 'claim-2' }
  ]
  let viewedKeys = readViewedDocumentKeys(storage)

  assert.equal(countNewDocuments(rows, viewedKeys), 2)
  assert.equal(isNewDocument(rows[0], viewedKeys), true)

  viewedKeys = markDocumentViewed(rows[0], viewedKeys, storage)

  assert.equal(countNewDocuments(rows, viewedKeys), 1)
  assert.equal(isNewDocument(rows[0], viewedKeys), false)
  assert.deepEqual([...readViewedDocumentKeys(storage)], ['archive:claim-1'])
})

test('document center sidebar inbox shares source scoped document keys', () => {
  const rows = buildDocumentInboxRows({
    ownedClaims: [{ id: 'claim-1', claim_no: 'EXP-1' }],
    approvalClaims: [{ id: 'claim-1', claim_no: 'EXP-1' }],
    archivedClaims: [{ id: 'claim-2', claim_no: 'EXP-2' }]
  })

  assert.deepEqual(rows.map((row) => resolveDocumentNewKey(row)), ['approval:claim-1', 'archive:claim-2'])
})

test('document center scope state restores only allowed tabs', () => {
  const storage = createMemoryStorage()
  const scopes = ['全部', '申请单', '报销单', '审核单', '归档']

  assert.equal(readDocumentScope('全部', scopes, storage), '全部')

  writeDocumentScope('归档', scopes, storage)
  assert.equal(readDocumentScope('全部', scopes, storage), '归档')

  writeDocumentScope('不存在', scopes, storage)
  assert.equal(readDocumentScope('全部', scopes, storage), '归档')
})
