import assert from 'node:assert/strict';
import test from 'node:test';
import {
  AUTH_COOKIE,
  createAuthManager,
  parseCookies,
  sessionCookie,
} from './auth.mjs';

test('auth manager issues, verifies, and revokes sessions', () => {
  const auth = createAuthManager({ password: 'secret', ttlMs: 1_000 });
  const login = auth.login('secret', '127.0.0.1', 100);

  assert.equal(login.ok, true);
  assert.equal(auth.verify(login.token, 200), true);
  auth.revoke(login.token);
  assert.equal(auth.verify(login.token, 300), false);
});

test('auth manager rate limits repeated failures', () => {
  const auth = createAuthManager({
    password: 'secret',
    maxFailures: 2,
    failureWindowMs: 1_000,
  });

  assert.equal(auth.login('wrong', 'client', 100).ok, false);
  assert.equal(auth.login('wrong', 'client', 200).ok, false);
  assert.equal(auth.login('secret', 'client', 300).retryAfterMs, 800);
  assert.equal(auth.login('secret', 'client', 1_200).ok, true);
});

test('cookie helpers preserve opaque tokens', () => {
  const cookie = sessionCookie('a/b+c', true);
  assert.match(cookie, /HttpOnly/);
  assert.match(cookie, /Secure/);
  assert.equal(parseCookies(cookie)[AUTH_COOKIE], 'a/b+c');
});
