using Microsoft.Extensions.Logging;
using RabbitMQ.Client;
using SumaTube.Infra.VideoSumarizer.Contracts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace SumaTube.Infra.VideoSumarizer.Videos
{
    public class VideoSumarizerService : IVideoSumarizerService
    {
        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-queue";

        private readonly ILogger<VideoSumarizerService> _logger;

        public VideoSumarizerService(ILogger<VideoSumarizerService> logger)
        {
            _logger = logger;
        }

        public async Task RequestVideoSummarization(string sessionId, string url, string language)
        {
            _logger.LogInformation("### Video Processor Publisher ###");
            _logger.LogInformation("Conectando ao RabbitMQ em {HostName}...", _hostName);

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

                using (var connection = await factory.CreateConnectionAsync())
                using (var channel = await connection.CreateChannelAsync())
                {
                    await channel.QueueDeclareAsync(
                                        queue: _queueName,
                                        durable: true,
                                        exclusive: false,
                                        autoDelete: false,
                                        arguments: null);

                    var properties = new BasicProperties
                    {
                        Persistent = true
                    };

                    _logger.LogInformation("Conexão estabelecida com RabbitMQ");

                    if (string.IsNullOrWhiteSpace(language))
                        language = "pt";

                    // Criar objeto de mensagem
                    var message = new VideoProcessingMessageDocument(
                        sessionId,
                        url,
                        language);

                    // Serializar para JSON
                    var messageJson = JsonSerializer.Serialize(message);
                    var body = Encoding.UTF8.GetBytes(messageJson);

                    // Publicar mensagem
                    await channel.BasicPublishAsync(
                        exchange: string.Empty,
                        routingKey: _queueName,
                        mandatory: true,
                        basicProperties: properties,
                        body: body);

                    _logger.LogInformation("Mensagem enviada: {Message}", messageJson);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Erro ao enviar mensagem para RabbitMQ: {Message}", ex.Message);
                throw;
            }
        }
    }
}
