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

import {
  buildWaterFacilityQuery,
  getRequestErrorMessage,
  normalizePipeStatus
} from '../src/utils/waterFacilityQuery.js'

test('buildWaterFacilityQuery maps date range to top-level backend contract', () => {
  const source = { pageNum: 2, pageSize: 20, pipeCode: 'P-1' }
  const query = buildWaterFacilityQuery(source, ['2026-01-01 00:00:00', '2026-01-31 23:59:59'])

  assert.deepEqual(query, {
    pageNum: 2,
    pageSize: 20,
    pipeCode: 'P-1',
    startTime: '2026-01-01 00:00:00',
    endTime: '2026-01-31 23:59:59'
  })
  assert.deepEqual(source, { pageNum: 2, pageSize: 20, pipeCode: 'P-1' })
  assert.equal(query.params, undefined)
})

test('buildWaterFacilityQuery removes stale dates when range is cleared', () => {
  const query = buildWaterFacilityQuery({ pageNum: 1, startTime: 'old', endTime: 'old' }, [])

  assert.equal(query.startTime, undefined)
  assert.equal(query.endTime, undefined)
  assert.equal(query.beginTime, undefined)
  assert.equal(query.params, undefined)
})

test('normalizePipeStatus accepts numeric and string status values', () => {
  assert.equal(normalizePipeStatus(0), '0')
  assert.equal(normalizePipeStatus('1'), '1')
  assert.equal(normalizePipeStatus(null), '')
})

test('getRequestErrorMessage exposes a useful server error', () => {
  assert.equal(getRequestErrorMessage({ response: { data: { msg: '数据库不可用' } } }, '查询失败'), '数据库不可用')
  assert.equal(getRequestErrorMessage(new Error('网络断开'), '查询失败'), '网络断开')
  assert.equal(getRequestErrorMessage({}, '查询失败'), '查询失败')
})

test('facility detail requests retain a retryable error state', () => {
  const pages = ['pipeInfo', 'waterPlant', 'pumpStation', 'waterSource', 'waterUserInfo']
  for (const page of pages) {
    const file = path.resolve('src/views/subSystem/basic', page, 'index.vue')
    const source = fs.readFileSync(file, 'utf8')
    const detailMethod = source.match(/handleDetail\(row\)\s*\{([\s\S]*?)\n\s*\},/)
    assert.ok(detailMethod, `${page} detail method should exist`)
    assert.match(detailMethod[1], /\.catch\(error => \{[\s\S]*?this\.errorMessage = getRequestErrorMessage\(/, page)
  }
})
