using System.Net;
using Autofac;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using PlanTempus.Core.SeqLogging;
using PlanTempus.Core.Telemetry;

namespace PlanTempus.X.TDD.Logging;

[TestClass]
public class SeqBackgroundServiceTest : TestFixture
{
    private CancellationTokenSource _cts;
    private IMessageChannel<ITelemetry> _messageChannel;
    private SeqBackgroundService _service;

    [TestInitialize]
    public void SetupThis()
    {
        _messageChannel = new MessageChannel();
        var telemetryClient = Container.Resolve<TelemetryClient>();

        var config = new SeqConfiguration("http://localhost:5341", null, "MSTEST");

        var httpClient = new SeqHttpClient(config);
        var logger = new SeqLogger<SeqBackgroundService>(httpClient, config);

        _service = new SeqBackgroundService(telemetryClient, _messageChannel, logger);
        _cts = new CancellationTokenSource();
    }

    [TestMethod]
    public async Task Messages_ShouldBeProcessedFromQueue()
    {
        await _service.StartAsync(_cts.Token);

        for (var i = 0; i < 5; i++)
        {
            var eventTelemetry = new EventTelemetry
            {
                Name = "Test Event",
                Timestamp = DateTimeOffset.UtcNow
            };
            eventTelemetry.Properties.Add("TestId", Guid.NewGuid().ToString());
            eventTelemetry.Metrics.Add("TestMetric", 42.0);

            await _messageChannel.Writer.WriteAsync(eventTelemetry);
        }

        // wait for processing
        await Task.Delay(5000);

        _cts.Cancel(); //not sure about this, we need to analyse more before this is "the way"
        await _service.StopAsync(CancellationToken.None);


        var hasMoreMessages = await _messageChannel.Reader.WaitToReadAsync();
        Assert.IsFalse(hasMoreMessages, "Queue should be empty after 5 seconds");
    }

    private class TestMessageHandler : HttpMessageHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken)
        {
            return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK));
        }
    }
}