import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import test from 'node:test'
import { readMonitoringExportError } from '../src/utils/waterSupplyModel.js'

test('water device exports download Excel blobs and surface backend JSON errors', async () => {
  const apiSource = await readFile('src/api/pipeNetwork/waterSupply.js', 'utf8')
  const pageSource = await readFile(
    'src/views/subSystem/waterSupply/components/WaterDevicePage.vue',
    'utf8'
  )

  const ledgerExport = apiSource.match(/export const exportDeviceLedger = .*$/mu)?.[0] || ''
  const abnormalExport = apiSource.match(/export const exportAbnormalDevices = .*$/mu)?.[0] || ''
  assert.match(ledgerExport, /responseType: 'blob'/u)
  assert.match(abnormalExport, /responseType: 'blob'/u)
  assert.match(pageSource, /readMonitoringExportError\(response\)/u)
  assert.match(pageSource, /saveAs\(blob/u)
})

test('water device ledger import and image display use the public contract', async () => {
  const apiSource = await readFile('src/api/pipeNetwork/waterSupply.js', 'utf8')
  const pageSource = await readFile(
    'src/views/subSystem/waterSupply/components/WaterDevicePage.vue',
    'utf8'
  )

  assert.match(apiSource, /export const importDeviceLedger = \(file, updateSupport = false\)/u)
  assert.match(apiSource, /url: '\/waterSupply\/device\/ledger\/import'/u)
  assert.match(pageSource, /importDeviceLedger/u)
  assert.match(pageSource, /供水设备批量导入/u)
  assert.match(pageSource, /importUpdateSupport/u)
  assert.match(pageSource, /row\.equipmentImage/u)
  assert.match(pageSource, /detail\.equipmentImage/u)
})

test('recognizes JSON export errors when the MIME includes a charset', async () => {
  const message = await readMonitoringExportError(
    new Blob(['{"msg":"导出失败"}'], { type: 'application/json;charset=UTF-8' })
  )
  assert.equal(message, '导出失败')
})

test('recognizes JSON export errors returned through an HTTP error response', async () => {
  const message = await readMonitoringExportError({
    type: 'application/json;charset=UTF-8',
    text: async () => '{"message":"没有导出权限"}'
  })
  assert.equal(message, '没有导出权限')
})
