using Exsersewo.Common.Extensions;
using Kynareth.Models;
using Microsoft.Extensions.Primitives;

namespace Kynareth.Helpers;

public static class RequestHelper
{
	public static string GetUrlHostname(this HttpContext context)
	{
		var origin = context.Request.Headers["X-Original-Host"];

		return origin.Count > 0 ? origin[0] : context.Request.Host.Host;
	}

	public static async Task<bool> IsRequestAuthenticatedAsync(this HttpRequest request)
	{
		string key = request.GetToken();

		if (string.IsNullOrWhiteSpace(key)) return false;

		await using var database = request.HttpContext.RequestServices.GetRequiredService<KynarethDbContext>();

		var tokenEntry = database.Tokens.FirstOrDefault(token => token.Token.Equals(key));

		if (tokenEntry is not { IsValid: true }) return false;

		return true;
	}

	public static string GetToken(this HttpRequest request)
	{
		if (!request.Headers.TryGetValue("Authorization", out StringValues authKey)) return string.Empty;

		if (!authKey.ToArray().AnyStartWith("Bearer", out string key)) return string.Empty;

		return key.Replace("Bearer ", "");
	}
}