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

import { parseRuntimeConfig } from "./env";

describe("runtime frontend configuration", () => {
  it("uses container-provided values without relying on Vite build variables", () => {
    expect(
      parseRuntimeConfig({
        TJWATER_MAPBOX_ACCESS_TOKEN: "token",
        TJWATER_MAP_URL: "https://maps.example.test/geoserver",
        TJWATER_GEOSERVER_WORKSPACE: "project-a",
        TJWATER_AGENT_API_BASE_URL: "https://agent.example.test",
        TJWATER_ENABLE_DEV_PANEL: "true",
        TJWATER_ENABLE_MSW: "false"
      })
    ).toEqual({
      TJWATER_MAPBOX_ACCESS_TOKEN: "token",
      TJWATER_MAP_URL: "https://maps.example.test/geoserver",
      TJWATER_GEOSERVER_WORKSPACE: "project-a",
      TJWATER_AGENT_API_BASE_URL: "https://agent.example.test",
      TJWATER_ENABLE_DEV_PANEL: true,
      TJWATER_ENABLE_MSW: false
    });
  });

  it("applies typed defaults for optional feature flags", () => {
    expect(parseRuntimeConfig({})).toMatchObject({
      TJWATER_ENABLE_DEV_PANEL: false,
      TJWATER_ENABLE_MSW: false
    });
  });

  it("rejects invalid runtime URLs before the application starts", () => {
    expect(() => parseRuntimeConfig({ TJWATER_MAP_URL: "not-a-url" })).toThrow();
  });

  it.each([
    ["TJWATER_MAP_URL", "file:///etc/passwd"],
    ["TJWATER_AGENT_API_BASE_URL", "https://user:secret@agent.example.test"],
    ["TJWATER_AGENT_API_BASE_URL", "https://agent.example.test/#secret"]
  ])("rejects unsafe browser runtime address %s", (key, value) => {
    expect(() => parseRuntimeConfig({ [key]: value })).toThrow();
  });
});
