/*
 * Copyright (C) Sapphirecode - All Rights Reserved
 * This file is part of auth-server-helper which is released under MIT.
 * See file 'LICENSE' for full license details.
 * Created by Timo Hocker <timo@scode.ovh>, May 2020
 */

/* eslint-disable no-magic-numbers */
// @ts-nocheck
'use strict';

const express = require ('express');
const auth = require ('./index');
const consts = require ('@sapphirecode/consts');
const crypto = require ('@sapphirecode/crypto-helper');
const password_helper = require ('@sapphirecode/password-helper');


/**
 * start the server
 */
async function start_server () {
  const app = express ();

  const id = 69;
  const name = 'testuser';
  const salt = crypto.create_salt ();
  const password = await password_helper.hash (
    crypto.hash_sha512 ('foo', salt)
  );
  const user = { id, name, salt, password };

  app.use (auth ((user_name) => {
    if (user.name === user_name)
      return user;

    return null;
  }, [
    /noauthreg/u,
    { method: 'POST', regex: /noauthobj/u }
  ]));

  app.use ((req, res) => {
    res.status (consts.http.status_ok)
      .end (`foo:${req.connection.user_id}`);
  });

  return new Promise ((res) => {
    const listener = app.listen (0, () => {
      res (listener.address ().port);
    });
  });
}

module.exports = { start_server };