import { describe, expect, test } from "bun:test";
import { buildAdapters, requireOffloadToken, resolveOffloadConnection } from "./index";
import { defaultConfig } from "../config";
import { CollectorFatalError } from "../errors";

const TOKEN = "test-collector-token";

describe("requireOffloadToken", () => {
  test("returns trimmed non-empty token", () => {
    expect(requireOffloadToken(`  ${TOKEN}  `)).toBe(TOKEN);
  });

  test("empty token throws CollectorFatalError with code TOKEN_EMPTY", () => {
    expect(() => requireOffloadToken("")).toThrow(CollectorFatalError);
    try {
      requireOffloadToken("   ");
    } catch (err) {
      expect(err).toBeInstanceOf(CollectorFatalError);
      expect((err as CollectorFatalError).code).toBe("TOKEN_EMPTY");
    }
  });
});

describe("resolveOffloadConnection", () => {
  test("resolves defaults and passes through validated token", () => {
    const connection = resolveOffloadConnection(defaultConfig(), TOKEN);
    expect(connection).toEqual({
      controllerUrl: "http://127.0.0.1:8787",
      metricsUrl: "http://127.0.0.1:8787",
      token: TOKEN,
    });
  });

  test("empty token throws TOKEN_EMPTY before connection is returned", () => {
    expect(() => resolveOffloadConnection(defaultConfig(), "")).toThrow(CollectorFatalError);
  });
});

describe("buildAdapters offload token", () => {
  test("empty token throws TOKEN_EMPTY when offload is enabled", () => {
    expect(() => buildAdapters(defaultConfig(), "")).toThrow(CollectorFatalError);
    try {
      buildAdapters(defaultConfig(), "");
    } catch (err) {
      expect((err as CollectorFatalError).code).toBe("TOKEN_EMPTY");
    }
  });
});
