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

import {
  buildFacilityMapModel,
  filterFacilityMapModel,
  findFacilityFeature
} from '../src/utils/waterFacilityGisModel.js'

const collection = {
  type: 'FeatureCollection',
  features: [
    {
      type: 'Feature',
      id: 'plant:1',
      geometry: { type: 'Point', coordinates: [113.1, 23.1] },
      properties: { facilityType: 'plant', id: 1, code: 'WP-1', name: '城北水厂', location: '城北路' }
    },
    {
      type: 'Feature',
      id: 'pipe:2',
      geometry: { type: 'LineString', coordinates: [[113.2, 23.2], [113.4, 23.4]] },
      properties: { facilityType: 'pipe', id: 2, code: 'PIPE-2', name: '输水干线', location: '滨江路' }
    },
    {
      type: 'Feature',
      id: 'user:3',
      geometry: { type: 'Point', coordinates: [113.5, null] },
      properties: { facilityType: 'user', id: 3, code: 'USER-3', name: '缺坐标用水户' }
    }
  ]
}

test('facility map model keeps WGS84 coordinate order and omits incomplete features', () => {
  const model = buildFacilityMapModel(collection)

  assert.deepEqual(model.points.map(item => [item.lng, item.lat]), [[113.1, 23.1]])
  assert.deepEqual(model.lines[0].points.map(item => [item.lng, item.lat]), [[113.2, 23.2], [113.4, 23.4]])
})

test('facility type filters produce an observable empty layer state', () => {
  const model = buildFacilityMapModel(collection)
  const visible = filterFacilityMapModel(model, { plant: false, pipe: false, user: true })

  assert.equal(visible.points.length, 0)
  assert.equal(visible.lines.length, 0)
  assert.equal(visible.isEmpty, true)
})

test('facility search locates points and line midpoints by name, code, or address', () => {
  const model = buildFacilityMapModel(collection)

  assert.deepEqual(findFacilityFeature(model, 'WP-1'), {
    ...model.points[0],
    kind: 'point'
  })
  assert.deepEqual(
    [findFacilityFeature(model, '滨江路').lng, findFacilityFeature(model, '滨江路').lat],
    [113.3, 23.3]
  )
})

test('GIS page exposes REST-backed right detail drawer and empty layer state', () => {
  const source = fs.readFileSync('src/views/subSystem/waterSupply/facility/gis.vue', 'utf8')

  assert.match(source, /<el-drawer[\s\S]*?direction="rtl"[\s\S]*?class="detail-drawer"/u)
  assert.match(source, /getWaterFacilityDetail\(feature\.type, feature\.id\)/u)
  assert.match(source, /detailLoading/u)
  assert.match(source, /detailError/u)
  assert.match(source, /当前筛选下没有可显示的供水设施/u)
})
