import test from 'node:test'
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import {
  buildThresholdQuery,
  buildThresholdSavePayload,
  buildThresholdUpdatePayload
} from '../src/utils/waterSupplyUiModel.js'

test('threshold page uses the water-only threshold device endpoint', async () => {
  const source = await readFile(
    'src/views/subSystem/waterSupply/components/WaterThresholdPage.vue',
    'utf8'
  )

  assert.match(source, /listThresholdDevices/u)
  assert.doesNotMatch(source, /listDeviceLedger/u)
})

test('threshold drawer follows the shared right-side detail drawer contract', async () => {
  const source = await readFile(
    'src/views/subSystem/waterSupply/components/WaterThresholdPage.vue',
    'utf8'
  )

  assert.match(source, /<el-drawer\b[^>]*direction="rtl"[^>]*>/u)
  assert.match(source, /<el-drawer\b[^>]*class="detail-drawer threshold-drawer"[^>]*>/u)
  assert.match(source, /\.threshold-drawer\s*\{\s*width:\s*100% !important/u)
})

test('builds the flat batch-save contract expected by the threshold API', () => {
  const payload = buildThresholdSavePayload({
    id: 'draft-id',
    deviceCodes: [' WS-FLOW-1 ', '', 'WS-FLOW-2', 'WS-FLOW-1'],
    warningType: ' 流量预警 ',
    warningCode: ' WARN-FLOW ',
    minValue: '20',
    maxValue: '40',
    periodStart: '08:00',
    periodEnd: '20:00',
    remark: ' 高峰期阈值 '
  })

  assert.deepEqual(payload, {
    deviceCodes: ['WS-FLOW-1', 'WS-FLOW-2'],
    warningType: '流量预警',
    warningCode: 'WARN-FLOW',
    minValue: 20,
    maxValue: 40,
    periodStart: '08:00',
    periodEnd: '20:00',
    remark: '高峰期阈值'
  })
})

test('builds an update payload that preserves the threshold id', () => {
  const payload = buildThresholdUpdatePayload({
    id: 'threshold-id',
    deviceCode: 'WS-FLOW-1',
    warningType: '流量预警',
    warningCode: 'WARN-FLOW',
    minValue: 20,
    maxValue: 40,
    periodStart: '08:00',
    periodEnd: '20:00',
    createTime: '2026-09-02 10:00:00'
  })

  assert.deepEqual(payload, {
    id: 'threshold-id',
    deviceCode: 'WS-FLOW-1',
    warningType: '流量预警',
    warningCode: 'WARN-FLOW',
    minValue: 20,
    maxValue: 40,
    periodStart: '08:00',
    periodEnd: '20:00'
  })
})

test('builds threshold list filters without alarm-only fields', () => {
  const query = buildThresholdQuery({
    pageNum: 2,
    pageSize: 20,
    deviceCode: 'WS-FLOW-1',
    warningType: '流量预警',
    keyword: ' ',
    alarmLevel: 2,
    alarmStatus: 0
  })

  assert.deepEqual(query, {
    pageNum: 2,
    pageSize: 20,
    deviceCode: 'WS-FLOW-1',
    warningType: '流量预警'
  })
})
