using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RabbitMQ.Client.Events;
using RabbitMQ.Client;
using SumaTube.Infra.Contracts.Repositories.Videos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static MongoDB.Driver.WriteConcern;

namespace SumaTube.Infra.VideoSumarizer.Videos
{
    public class VideoProcessingCompletedListener : BackgroundService
    {
        private readonly IVideoSummaryRepository _repository;
        private readonly ILogger<VideoProcessingCompletedListener> _logger;
        private IConnection _connection;
        //private IModel _channel;

        private static string _hostName = Environment.GetEnvironmentVariable("RABBITMQ_HOST") ?? "localhost";
        private static string _userName = Environment.GetEnvironmentVariable("RABBITMQ_USER") ?? "guest";
        private static string _password = Environment.GetEnvironmentVariable("RABBITMQ_PASSWORD") ?? "guest";
        private static string _queueName = "video-processing-completed";

        public VideoProcessingCompletedListener(
            IVideoSummaryRepository repository,
            ILogger<VideoProcessingCompletedListener> logger)
        {
            _repository = repository;
            _logger = logger;

            InitializeRabbitMQ();
        }

        private void InitializeRabbitMQ()
        {
            _logger.LogInformation("Inicializando conexão com RabbitMQ em {HostName}...", _hostName);

            try
            {
                //var factory = new ConnectionFactory()
                //{
                //    HostName = _hostName,
                //    UserName = _userName,
                //    Password = _password,
                //    DispatchConsumersAsync = true
                //};

                //_connection = factory.CreateConnection();
                //_channel = _connection.CreateModel();

                //_channel.QueueDeclare(
                //    queue: _queueName,
                //    durable: true,
                //    exclusive: false,
                //    autoDelete: false,
                //    arguments: null);

                _logger.LogInformation("Conexão com RabbitMQ estabelecida. Aguardando mensagens na fila: {QueueName}", _queueName);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Erro ao inicializar conexão com RabbitMQ: {Message}", ex.Message);
                throw;
            }
        }

        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            //stoppingToken.ThrowIfCancellationRequested();

            //var consumer = new AsyncEventingBasicConsumer(_channel);

            //consumer.Received += async (model, ea) =>
            //{
            //    var body = ea.Body.ToArray();
            //    var message = Encoding.UTF8.GetString(body);

            //    _logger.LogInformation("Mensagem recebida: {Message}", message);

            //    try
            //    {
            //        var completedMessage = JsonConvert.DeserializeObject<VideoProcessingCompletedMessage>(message);

            //        // Buscar o resumo pelo sessionId
            //        var summaries = await _repository.GetByUserIdAsync(completedMessage.UserId);
            //        var summary = summaries.Find(s => s.SessionId == completedMessage.SessionId);

            //        if (summary != null)
            //        {
            //            _logger.LogInformation("Atualizando resumo. ID: {Id}, SessionId: {SessionId}",
            //                summary.Id, completedMessage.SessionId);

            //            if (completedMessage.Success)
            //            {
            //                summary.SetAsCompleted(
            //                    completedMessage.Title,
            //                    completedMessage.Summary,
            //                    completedMessage.Transcription,
            //                    completedMessage.Duration);
            //            }
            //            else
            //            {
            //                summary.SetAsFailed(completedMessage.ErrorMessage);
            //            }

            //            await _repository.UpdateAsync(summary);
            //            _logger.LogInformation("Resumo atualizado com sucesso. ID: {Id}, Status: {Status}",
            //                summary.Id, summary.Status);
            //        }
            //        else
            //        {
            //            _logger.LogWarning("Resumo não encontrado para SessionId: {SessionId}", completedMessage.SessionId);
            //        }

            //        _channel.BasicAck(ea.DeliveryTag, false);
            //    }
            //    catch (Exception ex)
            //    {
            //        _logger.LogError(ex, "Erro ao processar mensagem: {Message}", ex.Message);
            //        _channel.BasicNack(ea.DeliveryTag, false, true);
            //    }
            //};

            //_channel.BasicConsume(queue: _queueName, autoAck: false, consumer: consumer);

            return Task.CompletedTask;
        }

        public override void Dispose()
        {
            //_channel?.Close();
            //_connection?.Close();
            base.Dispose();
        }
    }
}