import { describe, expect, it } from "vitest";
import {
  buildDevFrontAuthRedirectUris,
  canStartBrowserPkceLogin,
  DEVFRONT_AUTH_CALLBACK_PATH,
  resolveDevFrontPublicOrigin,
} from "./authConfig";

describe("devfront auth config", () => {
  it("builds callback URLs from the public origin", () => {
    expect(buildDevFrontAuthRedirectUris("https://sdev.hmac.kr")).toEqual({
      redirectUri: "https://sdev.hmac.kr/auth/callback",
      postLogoutRedirectUri: "https://sdev.hmac.kr",
      popupRedirectUri: "https://sdev.hmac.kr/auth/callback",
    });
  });

  it("uses the browser origin when the configured origin is empty or invalid", () => {
    expect(resolveDevFrontPublicOrigin("", "http://localhost:5173")).toBe(
      "http://localhost:5173",
    );
    expect(
      resolveDevFrontPublicOrigin("not a url", "http://localhost:5173"),
    ).toBe("http://localhost:5173");
  });

  it("keeps the callback path aligned with the registered redirect path", () => {
    expect(DEVFRONT_AUTH_CALLBACK_PATH).toBe("/auth/callback");
  });

  it("blocks browser PKCE login in an insecure context", () => {
    expect(
      canStartBrowserPkceLogin({
        isSecureContext: false,
        origin: "http://localhost:5174",
        cryptoSubtleAvailable: false,
      }),
    ).toBe(false);
    expect(
      canStartBrowserPkceLogin({
        isSecureContext: false,
        origin: "http://172.16.9.189:5174",
        cryptoSubtleAvailable: false,
      }),
    ).toBe(false);
    expect(
      canStartBrowserPkceLogin({
        isSecureContext: true,
        origin: "http://172.16.9.189:5174",
        cryptoSubtleAvailable: true,
      }),
    ).toBe(true);
  });

  it("allows host.docker.internal when WebCrypto is enabled by the browser", () => {
    expect(
      canStartBrowserPkceLogin({
        isSecureContext: false,
        origin: "http://host.docker.internal:5000",
        cryptoSubtleAvailable: true,
      }),
    ).toBe(true);
    expect(
      canStartBrowserPkceLogin({
        isSecureContext: false,
        origin: "http://host.docker.internal:5000",
        cryptoSubtleAvailable: false,
      }),
    ).toBe(false);
  });

  it("allows private network IPv4 origins when WebCrypto is enabled by the browser", () => {
    for (const origin of [
      "http://10.0.0.10:5000",
      "http://172.16.9.189:5000",
      "http://172.31.255.255:5000",
      "http://192.168.0.20:5000",
    ]) {
      expect(
        canStartBrowserPkceLogin({
          isSecureContext: false,
          origin,
          cryptoSubtleAvailable: true,
        }),
      ).toBe(true);
    }

    for (const origin of [
      "http://172.15.255.255:5000",
      "http://172.32.0.1:5000",
      "http://8.8.8.8:5000",
    ]) {
      expect(
        canStartBrowserPkceLogin({
          isSecureContext: false,
          origin,
          cryptoSubtleAvailable: true,
        }),
      ).toBe(false);
    }
  });
});
