using System.Net;
using System.Net.Http;
using System.Text;

namespace Elfisa.Tests;

/// <summary>Мок HttpMessageHandler: отдаёт заданные ответы или бросает ошибки.</summary>
internal sealed class FakeHttpHandler : HttpMessageHandler
{
    private readonly Func<HttpRequestMessage, int, HttpResponseMessage> _responder;
    public int Calls { get; private set; }
    public HttpRequestMessage? LastRequest { get; private set; }

    public FakeHttpHandler(Func<HttpRequestMessage, int, HttpResponseMessage> responder) => _responder = responder;

    public FakeHttpHandler(HttpStatusCode code, string body)
        : this((_, __) => Json(code, body)) { }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        LastRequest = request;
        var i = Calls++;
        return Task.FromResult(_responder(request, i));
    }

    public static HttpResponseMessage Json(HttpStatusCode code, string body) =>
        new(code) { Content = new StringContent(body, Encoding.UTF8, "application/json") };
}

/// <summary>Генератор JWT для тестов срока действия сессии.</summary>
internal static class Jwt
{
    public static long Now => DateTimeOffset.UtcNow.ToUnixTimeSeconds();

    private static string B64(string s) =>
        Convert.ToBase64String(Encoding.UTF8.GetBytes(s)).TrimEnd('=').Replace('+', '-').Replace('/', '_');

    public static string Make(long exp) => $"{B64("{\"alg\":\"HS256\"}")}.{B64($"{{\"exp\":{exp}}}")}.sig";

    public static string MakeNoExp() => $"{B64("{\"alg\":\"HS256\"}")}.{B64("{\"sub\":\"x\"}")}.sig";
}
