/*
Espe | Ein schlichtes Werkzeug zur Mitglieder-Verwaltung | Backend
Copyright (C) 2024 Christian Fraß

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public 
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later 
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied 
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see 
<https://www.gnu.org/licenses/>. 
 */

namespace _espe.service.admin
{
	
	/**
	 */
	export type type_value = {
		name : string;
		password_image : string;
	};
	
	
	/**
	 */
	function get(
		name : string
	) : (null | type_value)
	{
		const admins : Array<{name : string; password_image : string;}> = _espe.conf.get().admins;
		const entry : (undefined | {name : string; password_image : string;}) = admins.find(entry_ => (entry_.name === name));
		return (
			(entry === undefined)
			? null
			: {
				"name": entry.name,
				"password_image": entry.password_image,
			}
		);
	}
	
	
	/**
	 */
	async function check_password(
		value : type_value,
		password_given : string
	) : Promise<boolean>
	{
		return _espe.helpers.bcrypt_compare(value.password_image, password_given);
	}
	
	
	/**
	 */
	export async function login(
		name : string,
		password : string
	) : Promise<(null | type_value)>
	{
		const value : (null | type_value) = get(name);
		if (value === null) {
			return null;
		}
		else {
			if (! (await check_password(value, password))) {
				return null;
			}
			else {
				return value;
			}
		}
	}
	
}

