import { test } from "node:test";
import assert from "node:assert/strict";

import { conversationPageRouteKind, fetchConversations } from "./webClient.ts";

const originalFetch = globalThis.fetch;
const originalToken = process.env.DEWX_COMPANION_JWT;

function restoreGlobals() {
  globalThis.fetch = originalFetch;
  if (originalToken == null) {
    delete process.env.DEWX_COMPANION_JWT;
  } else {
    process.env.DEWX_COMPANION_JWT = originalToken;
  }
}

test.afterEach(restoreGlobals);

test("fetchConversations tries sync endpoint first and falls back to legacy on 404", async () => {
  process.env.DEWX_COMPANION_JWT = "test-token";
  const urls: string[] = [];
  globalThis.fetch = async (input) => {
    const url = String(input);
    urls.push(url);
    if (new URL(url).pathname === "/companion/sync/conversations") {
      return new Response("not deployed", { status: 404 });
    }
    return Response.json({
      success: true,
      data: [{ externalId: "old-1", channel: "LINKEDIN", accountId: "int1", lastTs: 1000, messages: [] }],
    });
  };

  const page = await fetchConversations({ limit: 25, since: 123, workspaceId: "ws1" });

  assert.equal(page.length, 1);
  assert.equal(conversationPageRouteKind(page), "legacy");
  assert.equal(urls.length, 2);

  const first = new URL(urls[0]);
  assert.equal(first.pathname, "/companion/sync/conversations");
  assert.equal(first.searchParams.get("limit"), "25");
  assert.equal(first.searchParams.get("since"), "123");
  assert.equal(first.searchParams.get("workspaceId"), "ws1");

  const second = new URL(urls[1]);
  assert.equal(second.pathname, "/api/auth/companion/conversations");
  assert.equal(second.searchParams.get("limit"), "25");
  assert.equal(second.searchParams.get("since"), "123");
  assert.equal(second.searchParams.has("workspaceId"), false);
});

test("fetchConversations marks sync endpoint pages when the new route wins", async () => {
  process.env.DEWX_COMPANION_JWT = "test-token";
  const urls: string[] = [];
  globalThis.fetch = async (input) => {
    const url = String(input);
    urls.push(url);
    return Response.json({
      success: true,
      data: [{ externalId: "new-1", channel: "LINKEDIN", accountId: "int1", lastTs: 2000, messages: [] }],
    });
  };

  const page = await fetchConversations({ limit: 25, workspaceId: "ws1" });

  assert.equal(page.length, 1);
  assert.equal(conversationPageRouteKind(page), "sync");
  assert.equal(urls.length, 1);
  const first = new URL(urls[0]);
  assert.equal(first.pathname, "/companion/sync/conversations");
  assert.equal(first.searchParams.get("workspaceId"), "ws1");
});
