import assert from "node:assert/strict";
import { describe, it } from "node:test";
import {
  isIceConfigGrantActive,
  isSafeIceUrl,
  parseIceConfigRequest,
  parseIceConfigResponse,
  type IceConfigGrant,
} from "../media/index.ts";

const request = () => ({
  type: "ice-config-request",
  protocolVersion: 1,
  requestId: "ice-request-1",
  binding: { officeId: "lumbridge-hq", levelId: "level-1", roomId: "lobby", screenId: "lobby-monitor" },
  credential: {
    sessionId: "opaque-session", participantId: "opaque-participant", role: "presenter", grantToken: "opaque-grant-token-value",
  },
});

const grant = (): IceConfigGrant => ({
  type: "ice-config-grant",
  protocolVersion: 1,
  requestId: "ice-request-1",
  issuedAtMs: 1_000,
  expiresAtMs: 601_000,
  iceServers: [
    { urls: ["stun:relay.example.test:3478"] },
    {
      urls: ["turn:relay.example.test:3478", "turns:relay.example.test:5349"],
      username: "1700000600:opaque_nonce_value",
      credential: "dGVzdF9jcmVkZW50aWFsX3ZhbHVl",
      credentialType: "password",
    },
  ],
});

describe("ICE configuration wire contract", () => {
  it("accepts exact requests and bounded ephemeral grants", () => {
    assert.equal(parseIceConfigRequest(request()).ok, true);
    assert.equal(parseIceConfigRequest({
      ...request(),
      credential: { ...request().credential, sessionId: "_opaque-session", participantId: "-opaque-participant" },
    }).ok, true, "accepts every server-generated base64url prefix");
    assert.equal(parseIceConfigResponse(JSON.parse(JSON.stringify(grant()))).ok, true);
    assert.equal(isIceConfigGrantActive(grant(), 300_000), true);
    assert.equal(isIceConfigGrantActive(grant(), 601_000), false);
  });

  it("allows only credential-free ICE URL forms", () => {
    for (const url of [
      "stun:relay.example.test:3478", "stuns:relay.example.test:5349",
      "turn:192.0.2.4:3478", "turn:relay.example.test:3478?transport=udp",
      "turn:relay.example.test:3478?transport=tcp", "turns:[2001:db8::1]:5349?transport=tcp",
    ]) {
      assert.equal(isSafeIceUrl(url), true, url);
    }
    for (const url of [
      "https://relay.example.test", "turn:user:pass@relay.example.test:3478",
      "turn:relay.example.test:3478?credential=secret", "turn://relay.example.test:3478",
      "stun:relay.example.test:3478?transport=udp", "turn:relay.example.test:3478?transport=sctp",
      "turn:relay.example.test:3478?transport=tcp&credential=secret",
      "turn:relay.example.test:99999", "turn:relay example.test:3478",
    ]) assert.equal(isSafeIceUrl(url), false, url);
  });

  it("rejects extra keys, credential tricks, missing TURN, and excessive lifetime", () => {
    assert.equal(parseIceConfigRequest({ ...request(), subject: "stable-user" }).ok, false);
    const { credential: _credential, ...withoutCredential } = request();
    assert.equal(parseIceConfigRequest(withoutCredential).ok, false);
    assert.equal(parseIceConfigRequest({ ...request(), binding: { ...request().binding, screenId: "bad id" } }).ok, false);
    assert.equal(parseIceConfigResponse({ ...grant(), identity: { profile: "karti" } }).ok, false);
    assert.equal(parseIceConfigResponse({ ...grant(), iceServers: [{ urls: ["stun:relay.example.test:3478"] }] }).ok, false);
    assert.equal(parseIceConfigResponse({ ...grant(), expiresAtMs: 3_601_001 }).ok, false);
    const turn = grant().iceServers[1] as unknown as Record<string, unknown>;
    assert.equal(parseIceConfigResponse({
      ...grant(), iceServers: [{ ...turn, urls: ["turn:user@relay.example.test:3478"] }],
    }).ok, false);
  });
});
