import { describe, it, expect } from "vitest";
import { truncateIp } from "./truncate-ip";

describe("truncateIp", () => {
  describe("IPv4", () => {
    it("truncates to /24 (zeros the last octet)", () => {
      expect(truncateIp("192.168.1.42")).toBe("192.168.1.0");
      expect(truncateIp("10.0.0.255")).toBe("10.0.0.0");
      expect(truncateIp("8.8.8.8")).toBe("8.8.8.0");
    });

    it("throws on malformed input", () => {
      expect(() => truncateIp("192.168.1")).toThrow(/malformed IPv4/);
      expect(() => truncateIp("192.168.1.foo")).toThrow(/malformed IPv4/);
      expect(() => truncateIp("a.b.c.d")).toThrow(/malformed IPv4/);
    });

    it("throws on empty string", () => {
      expect(() => truncateIp("")).toThrow(/malformed IPv4/);
    });
  });

  describe("IPv6", () => {
    it("truncates to /48 (keeps first 3 hextets)", () => {
      expect(truncateIp("2001:0db8:1234:5678:abcd:ef00:1234:5678")).toBe("2001:0db8:1234::");
      expect(truncateIp("2001:0db8:abcd:1234::")).toBe("2001:0db8:abcd::");
    });

    it("lowercases hextets", () => {
      expect(truncateIp("2001:0DB8:ABCD:5678::")).toBe("2001:0db8:abcd::");
    });

    it("throws on too-few hextets", () => {
      expect(() => truncateIp("2001:0db8")).toThrow(/malformed IPv6/);
    });
  });
});
