import { describe, expect, it } from "vitest";

import {
  baseURLForPort,
  parseEnvFile,
  preflight,
  redact,
  waitForServer,
} from "../../scripts/run-geo-sample-e2e.mjs";

describe("run-geo-sample-e2e helpers", () => {
  it("parses simple dotenv files while ignoring comments", () => {
    expect(
      parseEnvFile(`
# comment
API_ACCESS_KEY=local-dev-key
DEEPSEEK_API_KEY="secret"
EMPTY=
`),
    ).toEqual({
      API_ACCESS_KEY: "local-dev-key",
      DEEPSEEK_API_KEY: "secret",
      EMPTY: "",
    });
  });

  it("requires a provider key in live mode", () => {
    expect(() =>
      preflight(
        {
          API_ACCESS_KEY: "local-dev-key",
          LLM_PROVIDER: "deepseek",
        },
        "deepseek",
      ),
    ).toThrow("DEEPSEEK_API_KEY is required for live sample E2E");
  });

  it("uses localhost for Next dev URLs", () => {
    expect(baseURLForPort(3000)).toBe("http://localhost:3000");
  });

  it("redacts configured secrets from logs", () => {
    expect(
      redact("x-api-key: local-dev-key provider secret", [
        "local-dev-key",
        "provider secret",
      ]),
    ).toBe("x-api-key: [REDACTED] [REDACTED]");
  });

  it("fails fast when the dev server process exits before readiness", async () => {
    await expect(
      waitForServer("http://127.0.0.1:9", 1000, {
        exitCode: 1,
      }),
    ).rejects.toThrow("dev server exited before http://127.0.0.1:9 became ready");
  });
});
