import express from 'express';
import assert from 'node:assert/strict';
import { describe, it } from 'node:test';
import extractSecrets from '../../src/middlewares/secrets.js';
import { BadRequestError } from '../../src/httpErrors.js';

describe('secrets middleware', () => {
  it('uses header', () => {
    const secrets = Buffer.from(
      JSON.stringify({
        chut: 'abc',
      }),
    ).toString('base64');

    const request = { header: (_key: string) => secrets } as express.Request;
    const response = { locals: {} } as express.Response;

    extractSecrets(request, response, () => {});

    assert.deepEqual(response.locals, {
      secrets: {
        chut: 'abc',
      },
    });
  });

  it('malformed header', async () => {
    const request = { header: (_key: string) => 'nope' } as express.Request;
    const response = { locals: {} } as express.Response;

    assert.throws(() => extractSecrets(request, response, () => {}), BadRequestError);
  });

  it('undefined', () => {
    const response = { locals: {} } as express.Response;

    assert.deepEqual(response.locals, {});
  });
});
