import test from "node:test";
import assert from "node:assert/strict";
import { signSession, verifySession, passwordMatches, __testSecret } from "./session.ts";

test("signSession/verifySession: gültiges Token wird akzeptiert", () => {
  process.env.SESSION_SECRET = __testSecret();
  process.env.ADMIN_PASSWORD = "test-password-123";
  const token = signSession();
  assert.equal(verifySession(token), true);
});

test("verifySession: leerer / falscher Token wird abgelehnt", () => {
  process.env.SESSION_SECRET = __testSecret();
  process.env.ADMIN_PASSWORD = "test-password-123";
  assert.equal(verifySession(undefined), false);
  assert.equal(verifySession(null), false);
  assert.equal(verifySession(""), false);
  assert.equal(verifySession("abc.def"), false);
  assert.equal(verifySession("aaaa.bbbb"), false);
});

test("verifySession: Token mit manipulierter Signatur wird abgelehnt", () => {
  process.env.SESSION_SECRET = __testSecret();
  process.env.ADMIN_PASSWORD = "test-password-123";
  const token = signSession();
  const [p, s] = token.split(".");
  // Flippe das letzte Zeichen der Signatur.
  const tampered = `${p}.${s.slice(0, -1)}${s.endsWith("A") ? "B" : "A"}`;
  assert.equal(verifySession(tampered), false);
});

test("passwordMatches: konstantes Timing, akzeptiert nur exakt gleiches Passwort", () => {
  process.env.SESSION_SECRET = __testSecret();
  process.env.ADMIN_PASSWORD = "test-password-123";
  assert.equal(passwordMatches("test-password-123"), true);
  assert.equal(passwordMatches("test-password-12"), false);
  assert.equal(passwordMatches("test-password-1234"), false);
  assert.equal(passwordMatches(""), false);
});

test("passwordMatches: wirft bei zu kurzem Passwort", () => {
  process.env.SESSION_SECRET = __testSecret();
  process.env.ADMIN_PASSWORD = "short";
  assert.throws(() => passwordMatches("anything"));
});
