using EonaCat.Json;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;

// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.

namespace EonaCat.Logger.EonaCatCoreLogger
{
    public sealed class SlackLogger : ILogger, IDisposable
    {
        private readonly string _categoryName;
        private readonly SlackLoggerOptions _options;
        private readonly LoggerScopedContext _context = new();
        private readonly Channel<string> _logChannel;
        private readonly HttpClient _httpClient;
        private readonly CancellationTokenSource _cts = new();
        private readonly Task _processingTask;

        private const int MaxQueueSize = 1000;

        public bool IncludeCorrelationId { get; set; }
        public event EventHandler<Exception> OnException;

        public SlackLogger(string categoryName, SlackLoggerOptions options)
        {
            _categoryName = categoryName ?? throw new ArgumentNullException(nameof(categoryName));
            _options = options ?? throw new ArgumentNullException(nameof(options));
            IncludeCorrelationId = options.IncludeCorrelationId;

            _httpClient = new HttpClient();

            // Bounded channel to prevent unbounded memory growth
            _logChannel = Channel.CreateBounded<string>(new BoundedChannelOptions(MaxQueueSize)
            {
                FullMode = BoundedChannelFullMode.DropOldest,
                SingleReader = true,
                SingleWriter = false
            });

            _processingTask = Task.Run(() => ProcessLogQueueAsync(_cts.Token), _cts.Token);
        }

        public IDisposable BeginScope<TState>(TState state) => null;
        public bool IsEnabled(LogLevel logLevel) => _options.IsEnabled;

        public void SetContext(string key, string value) => _context.Set(key, value);
        public void ClearContext() => _context.Clear();
        public string GetContext(string key) => _context.Get(key);

        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state,
            Exception exception, Func<TState, Exception, string> formatter)
        {
            if (!IsEnabled(logLevel) || formatter == null)
            {
                return;
            }

            try
            {
                if (IncludeCorrelationId)
                {
                    var correlationId = _context.Get("CorrelationId") ?? Guid.NewGuid().ToString();
                    _context.Set("CorrelationId", correlationId);
                }

                var message = formatter(state, exception);

                // Build Slack message
                var sb = new StringBuilder(256);
                sb.AppendLine($"*[{DateTime.UtcNow:u}]*");
                sb.AppendLine($"*[{logLevel}]*");
                sb.AppendLine($"*[{_categoryName}]*");
                sb.AppendLine($"Message: {message}");

                foreach (var kvp in _context.GetAll())
                {
                    sb.AppendLine($"_{kvp.Key}_: {kvp.Value}");
                }

                if (exception != null)
                {
                    sb.AppendLine($"Exception: {exception}");
                }

                // Drops oldest if full
                _logChannel.Writer.TryWrite(sb.ToString());
            }
            catch (Exception ex)
            {
                OnException?.Invoke(this, ex);
            }
        }

        private async Task ProcessLogQueueAsync(CancellationToken token)
        {
            try
            {
                await foreach (var message in _logChannel.Reader.ReadAllAsync(token))
                {
                    try
                    {
                        var payload = new { text = message };
                        using var content = new StringContent(JsonHelper.ToJson(payload), Encoding.UTF8, "application/json");

                        var response = await _httpClient.PostAsync(_options.WebhookUrl, content, token).ConfigureAwait(false);

                        if (!response.IsSuccessStatusCode)
                        {
                            OnException?.Invoke(this, new Exception($"Slack webhook failed: {response.StatusCode}"));
                        }
                    }
                    catch (Exception ex)
                    {
                        OnException?.Invoke(this, ex);
                    }
                }
            }
            catch (OperationCanceledException) 
            {
                // normal shutdown
            }
            catch (Exception ex)
            {
                OnException?.Invoke(this, ex);
            }
        }

        public void Dispose()
        {
            _cts.Cancel();
            _logChannel.Writer.Complete();

            try
            {
                _processingTask.Wait();
            }
            catch 
            {
                // Do nothing
            }

            _cts.Dispose();
            _httpClient.Dispose();
        }
    }
}
