import assert from "node:assert/strict"
import { mkdtempSync, rmSync } from "node:fs"
import os from "node:os"
import path from "node:path"

const dir = mkdtempSync(path.join(os.tmpdir(), "mm-flow-purge-"))
process.env.DATABASE_PATH = path.join(dir, "test.db")

const { sqliteDatabase } = await import("../db/index.js")
const {
  getFlowRuntimeCounters,
  purgeTrafficFlowStore,
  stopTrafficFlowListener,
} = await import("./traffic-flow-ingest.js")

function count(name: string): number {
  const row = sqliteDatabase.prepare(`SELECT COUNT(*) AS n FROM ${name}`).get() as { n: number }
  return Number(row?.n) || 0
}

try {
  sqliteDatabase.prepare(`
    INSERT INTO servers (name, host) VALUES ('purge-test', '127.0.0.1')
  `).run()
  const serverId = Number(
    (sqliteDatabase.prepare(`SELECT id FROM servers WHERE name = 'purge-test'`).get() as { id: number }).id,
  )
  sqliteDatabase.prepare(`
    INSERT INTO flow_buckets (server_id, bucket_at, src, dst, proto, src_port, dst_port, bytes, packets, in_iface)
    VALUES (?, '2026-01-01T00:00:00.000Z', '10.0.0.1', '8.8.8.8', 6, 50000, 443, 100, 1, 'wg-flow')
  `).run(serverId)
  sqliteDatabase.prepare(`
    INSERT INTO flow_minute_stats (server_id, bucket_at, bytes, packets, unique_src, unique_dst, conversations)
    VALUES (?, '2026-01-01T00:00:00.000Z', 100, 1, 1, 1, 1)
  `).run(serverId)
  sqliteDatabase.prepare(`
    INSERT INTO flow_minute_dims (server_id, bucket_at, dim, key, bytes, packets)
    VALUES (?, '2026-01-01T00:00:00.000Z', 'country', 'RU', 100, 1)
  `).run(serverId)
  sqliteDatabase.prepare(`
    INSERT INTO flow_daily_dims (server_id, day, dim, key, bytes, packets)
    VALUES (?, '2026-01-01', 'country', 'RU', 100, 1)
  `).run(serverId)
  sqliteDatabase.prepare(`
    INSERT INTO flow_ip_meta (prefix, asn, country, holder, ok, fetched_at)
    VALUES ('8.8.8.0/24', 15169, 'US', 'Google', 1, '2026-01-01T00:00:00.000Z')
  `).run()
  sqliteDatabase.prepare(`
    UPDATE traffic_flow_settings SET packets_received = 42, last_exporter_ip = '10.255.254.3' WHERE id = 1
  `).run()

  const result = await purgeTrafficFlowStore()
  stopTrafficFlowListener()

  assert.equal(result.ok, true)
  assert.equal(result.deleted.buckets, 1)
  assert.equal(result.deleted.minuteStats, 1)
  assert.equal(result.deleted.minuteDims, 1)
  assert.equal(result.deleted.dailyDims, 1)
  assert.equal(count("flow_buckets"), 0)
  assert.equal(count("flow_minute_stats"), 0)
  assert.equal(count("flow_minute_dims"), 0)
  assert.equal(count("flow_daily_dims"), 0)
  assert.equal(count("flow_ip_meta"), 1)
  assert.equal(count("servers"), 1)
  assert.equal(getFlowRuntimeCounters().packetsReceived, 0)
  assert.equal(getFlowRuntimeCounters().lastExporterIp, null)
} finally {
  try {
    sqliteDatabase.close()
  } catch {
    /* ignore */
  }
  rmSync(dir, { recursive: true, force: true })
}

console.log("traffic-flow-purge.test.ts: ok")
