import { expect, test } from "bun:test";
import { readAuthConfig } from "./config";

test("reads the active environment's APP_ORIGIN and normalizes it", () => {
  expect(readAuthConfig({ APP_ORIGIN: " http://127.0.0.1:4000/ " }).origin).toBe("http://127.0.0.1:4000");
  expect(readAuthConfig({ NODE_ENV: "production", APP_ORIGIN: "https://habits.example.com" }).origin).toBe("https://habits.example.com");
});

test("only development defaults to the local port", () => {
  expect(readAuthConfig({}).origin).toBe("http://127.0.0.1:3000");
  expect(readAuthConfig({ PORT: "4000" }).origin).toBe("http://127.0.0.1:4000");
  expect(() => readAuthConfig({ NODE_ENV: "production", APP_ORIGIN: " " })).toThrow("Set APP_ORIGIN");
});

test("rejects invalid origins and allows explicitly configured local production testing", () => {
  for (const value of ["not a URL", "http://habits.example.com", "https://habits.example.com/path"]) {
    expect(() => readAuthConfig({ NODE_ENV: "production", APP_ORIGIN: value })).toThrow("APP_ORIGIN");
  }
  expect(readAuthConfig({ NODE_ENV: "production", APP_ORIGIN: "http://127.0.0.1:3000" }).origin).toBe("http://127.0.0.1:3000");
});
