#!/bin/sh
# Functional autopkgtest for node-express-rate-limit: mount the middleware on a
# real Express app and check that requests beyond the limit get HTTP 429. Also
# exercises ipKeyGenerator on an IPv6 address, which relies on ip-address >= 10
# (Address6.networkForm()).
set -e

WORKDIR="${AUTOPKGTEST_TMP:-/tmp}"

# ESM bare imports don't honour Debian's global /usr/share/nodejs path, so link
# the modules the test imports by name into a local node_modules directory.
mkdir -p "$WORKDIR/node_modules"
for m in express express-rate-limit ip-address; do
    ln -sf "/usr/share/nodejs/$m" "$WORKDIR/node_modules/$m"
done

cat > "$WORKDIR/erl-test.mjs" <<'NODE'
import http from 'node:http';
import express from 'express';
import rateLimit, { ipKeyGenerator } from 'express-rate-limit';

let failures = 0;
const check = (ok, msg) => {
  console.log(`${ok ? 'ok' : 'not ok'} - ${msg}`);
  if (!ok) failures += 1;
};

check(typeof rateLimit === 'function', 'default export is the rateLimit function');

const app = express();
app.use(rateLimit({ windowMs: 60_000, limit: 2, standardHeaders: true, legacyHeaders: false }));
app.get('/', (request, response) => response.send('ok'));

const server = await new Promise((resolve) => {
  const s = app.listen(0, '127.0.0.1', () => resolve(s));
});
const { port } = server.address();

const get = () =>
  new Promise((resolve) => {
    http.get({ host: '127.0.0.1', port, path: '/' }, (res) => {
      res.resume();
      resolve(res.statusCode);
    });
  });

const c1 = await get();
const c2 = await get();
const c3 = await get();
check(c1 === 200, `first request allowed (got ${c1})`);
check(c2 === 200, `second request allowed (got ${c2})`);
check(c3 === 429, `third request rate-limited (got ${c3})`);

// IPv4 is returned as-is
check(ipKeyGenerator('1.2.3.4') === '1.2.3.4', 'ipKeyGenerator returns IPv4 unchanged');
// IPv6 uses ip-address Address6.networkForm() (requires ip-address >= 10)
const key6 = ipKeyGenerator('2001:db8::dead:beef', 56);
check(typeof key6 === 'string' && key6.startsWith('2001:db8'), `ipKeyGenerator handles IPv6 subnets (got ${key6})`);

server.close();
if (failures > 0) {
  console.error(`${failures} check(s) failed`);
  process.exit(1);
}
console.log('All express-rate-limit checks passed');
NODE

cd "$WORKDIR"
node "$WORKDIR/erl-test.mjs"
