import { beforeEach, describe, expect, it, vi } from "vitest";
import { validateSiteAgent } from "./client";

vi.mock("node:dns/promises", () => ({ lookup: vi.fn(async () => [{ address: "203.0.113.10" }]) }));

describe("Site Agent validation", () => {
  beforeEach(() => vi.restoreAllMocks());

  it("sends the plugin token with timestamp and nonce headers", async () => {
    const fetchMock = vi.fn(async (_url: URL, options: RequestInit) => {
      const headers = new Headers(options.headers);
      expect(headers.get("X-Site-Agent-Token")).toBe("test-token");
      expect(Number(headers.get("X-Site-Agent-Timestamp"))).toBeGreaterThan(0);
      expect(headers.get("X-Site-Agent-Nonce")).toMatch(/^[a-f0-9-]{36}$/);
      return new Response(JSON.stringify({ success: true, site_id: "site-123", version: "0.14.18" }), { status: 200 });
    });
    vi.stubGlobal("fetch", fetchMock);
    try {
      const result = await validateSiteAgent("https://example.com", "test-token");
      expect(result.siteId).toBe("site-123");
      expect(fetchMock).toHaveBeenCalledOnce();
    } finally {
      vi.unstubAllGlobals();
    }
  });
});
