import assert from 'node:assert/strict'

import {
  buildSpreadsheetChangeRecords,
  resolveSpreadsheetOperationLabel
} from '../src/views/scripts/spreadsheetChangeRecords.js'

function testResolveSpreadsheetOperationLabelFromHistorySource() {
  assert.equal(
    resolveSpreadsheetOperationLabel({
      spreadsheetMeta: { source: 'onlyoffice' },
      note: 'ONLYOFFICE 编辑保存规则表。'
    }),
    '在线编辑保存'
  )

  assert.equal(
    resolveSpreadsheetOperationLabel({
      spreadsheetMeta: { source: 'content-import' }
    }),
    '导入表格'
  )
}

function testBuildSpreadsheetChangeRecordsPrefersUnpublishedHistory() {
  const records = buildSpreadsheetChangeRecords({
    publishedVersion: 'v1.0.0',
    history: [
      {
        version: 'v1.0.1',
        note: 'ONLYOFFICE 编辑保存规则表。',
        createdBy: '张三',
        createdAt: '2026-05-18T10:00:00Z',
        isWorking: true,
        spreadsheetMeta: { source: 'onlyoffice' }
      },
      {
        version: 'v1.0.0',
        note: '首个上线版本',
        createdBy: '系统',
        createdAt: '2026-05-18T09:00:00Z',
        isWorking: false,
        spreadsheetMeta: { source: 'upload' }
      }
    ]
  })

  assert.deepEqual(
    records.map((item) => [item.version, item.operationLabel]),
    [['v1.0.1', '在线编辑保存']]
  )
}

function testBuildSpreadsheetChangeRecordsKeepsPendingLocalEditFirst() {
  const records = buildSpreadsheetChangeRecords({
    publishedVersion: 'v1.0.0',
    localRecords: [
      {
        version: 'v1.0.1',
        operationLabel: '编辑中',
        operationActor: '李四',
        note: '检测到未保存的表格改动，保存后会生成新版本并可查看差异。',
        time: '2026-05-18T10:30:00Z',
        isPendingLocalEdit: true,
        disabledReason: '当前是本地未保存修改，保存后才会生成可对比的版本。'
      }
    ],
    history: [
      {
        version: 'v1.0.1',
        note: 'ONLYOFFICE 编辑保存规则表。',
        createdBy: '李四',
        createdAt: '2026-05-18T10:00:00Z',
        isWorking: true,
        spreadsheetMeta: { source: 'onlyoffice' }
      }
    ]
  })

  assert.equal(records[0].operationLabel, '编辑中')
  assert.equal(records[0].isPendingLocalEdit, true)
  assert.equal(records[1].operationLabel, '在线编辑保存')
}

function run() {
  testResolveSpreadsheetOperationLabelFromHistorySource()
  testBuildSpreadsheetChangeRecordsPrefersUnpublishedHistory()
  testBuildSpreadsheetChangeRecordsKeepsPendingLocalEditFirst()
  console.log('spreadsheet change record tests passed')
}

run()
