import assert from 'node:assert/strict'
import { readdir, readFile } from 'node:fs/promises'
import { join } from 'node:path'
import test from 'node:test'

async function listVueFiles(directory) {
  const entries = await readdir(directory, { withFileTypes: true })
  const files = await Promise.all(entries.map(entry => {
    const path = join(directory, entry.name)
    return entry.isDirectory() ? listVueFiles(path) : path.endsWith('.vue') ? [path] : []
  }))
  return files.flat()
}

test('all read-only detail views use the shared right-side drawer', async () => {
  const views = await listVueFiles('src/views')
  for (const view of views) {
    const source = await readFile(view, 'utf8')
    const detailDialogs = source.match(/<el-dialog\b[^>]*(?:详情|详细|查看|预览|报警位置地图|视频查看|研判分析|催办记录|监测告警联动|全屏监控)[^>]*>/gu) || []
    assert.deepEqual(detailDialogs, [], view)

    const drawers = source.match(/<el-drawer\b[^>]*>/gu) || []
    for (const drawer of drawers) {
      assert.match(drawer, /direction=["']rtl["']/u, `${view}: ${drawer}`)
      if (!drawer.includes('facility-form-drawer')) {
        assert.match(drawer, /class=["'][^"']*detail-drawer/u, `${view}: ${drawer}`)
      }
    }
  }
})

test('operation forms remain dialogs instead of being treated as read-only details', async () => {
  const devicePage = await readFile('src/views/subSystem/waterSupply/components/WaterDevicePage.vue', 'utf8')

  const alarmPage = await readFile('src/views/subSystem/waterSupply/components/WaterAlarmPage.vue', 'utf8')
  assert.match(devicePage, /<el-dialog[^>]*title="设备维修派单"/u)
  assert.match(alarmPage, /<el-dialog[^>]*title="报警维修派单"/u)
})

test('water facility edit forms and table actions use the shared drawer and action styles', async () => {
  const facilityViews = [
    'src/views/subSystem/basic/pipeInfo/index.vue',
    'src/views/subSystem/basic/pumpStation/index.vue',
    'src/views/subSystem/basic/waterPlant/index.vue',
    'src/views/subSystem/basic/waterSource/index.vue',
    'src/views/subSystem/basic/waterUserInfo/index.vue'
  ]

  for (const view of facilityViews) {
    const source = await readFile(view, 'utf8')
    assert.match(source, /<el-drawer[^>]*:title="dialogTitle"[^>]*class="facility-form-drawer"[^>]*direction="rtl"/u, view)
    assert.match(source, /class="facility-row-actions"/u, view)
    assert.match(source, /class="facility-row-action is-detail"/u, view)
    assert.match(source, /class="facility-row-action is-edit"/u, view)
    assert.match(source, /class="facility-row-action is-delete"/u, view)
  }
})
