import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { readNetworkActivity } from "../src/network-activity.js";

const directories: string[] = [];

afterEach(async () => {
  await Promise.all(directories.splice(0).map((directory) => rm(directory, { recursive: true, force: true })));
});

describe("network activity snapshot", () => {
  it("accepts only bounded sanitized observer output", async () => {
    const directory = await mkdtemp(join(tmpdir(), "pi-car-activity-test-"));
    directories.push(directory);
    const path = join(directory, "activity.json");
    await writeFile(path, JSON.stringify({
      collectedAt: "2026-07-31T20:00:00.000Z",
      clients: [{ ipAddress: "10.42.0.20", macAddress: "aa:bb:cc:dd:ee:ff", hostname: "head-unit", leaseExpiresAt: null, state: "REACHABLE", connected: true }],
      dnsQueries: [{ timestamp: "2026-07-31T20:00:00.000Z", clientAddress: "10.42.0.20", type: "A", name: "example.com" }],
      flows: [{ protocol: "tcp", state: "ESTABLISHED", sourceAddress: "10.42.0.20", sourcePort: 50000, destinationAddress: "1.1.1.1", destinationPort: 443, packets: 4, bytes: 1000 }],
      dnsAvailable: true,
      flowsAvailable: true,
      messages: []
    }));
    await expect(readNetworkActivity(path)).resolves.toMatchObject({ supported: true, clients: [{ hostname: "head-unit" }] });
  });

  it("does not expose malformed observer files", async () => {
    const directory = await mkdtemp(join(tmpdir(), "pi-car-activity-test-"));
    directories.push(directory);
    const path = join(directory, "activity.json");
    await writeFile(path, '{"clients":"not-an-array"}');
    await expect(readNetworkActivity(path)).resolves.toMatchObject({ supported: false, clients: [] });
  });
});
