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

/* eslint-disable no-magic-numbers */
// @ts-nocheck

'use strict';

const crypto = require ('@scode/crypto-helper');
const consts = require ('@scode/consts');
const fetch = require ('node-fetch');

/**
 * login
 *
 * @param {string} user username
 * @param {string} password plain text password
 * @param {string} host host to login on
 */
async function login (user, password, host = '') {
  const salt_str = await fetch (`${host}/auth`, { headers: { user } })
    .then (async (res) => {
      if (res.status !== consts.http.status_ok)
        return '';

      const session_id = await res.text ();
      return session_id;
    });

  if (salt_str === '')
    throw new Error ('user or password invalid');

  const key = crypto.hash_sha512 (password, salt_str);

  return fetch (`${host}/auth`, { headers: { user, key } })
    .then ((res) => {
      if (res.status !== consts.http.status_ok)
        throw new Error ('user or password invalid');
      return res.text ();
    });
}

module.exports = { login };