using SendGrid;
using SendGrid.Helpers.Mail;


namespace WebVentaCoche.Services
{
    public class EmailService
    {
        private readonly string _apiKey;
        private readonly string _fromEmail;
        private readonly string _fromName;

        public EmailService(IConfiguration configuration)
        {
            // Leer configuraciones desde appsettings.json
            _apiKey = configuration["SendGrid:ApiKey"];
            _fromEmail = configuration["SendGrid:FromEmail"];
            _fromName = configuration["SendGrid:FromName"];
        }

        public async Task SendEmailAsync(string to, string subject, string htmlContent)
        {
            // Crear cliente SendGrid
            var client = new SendGridClient(_apiKey);

            // Configurar remitente y destinatario
            var from = new EmailAddress(_fromEmail, _fromName);
            var toEmail = new EmailAddress(to);

            // Convertir el contenido HTML a texto plano eliminando etiquetas
            var plainTextContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, "<[^>]+>", string.Empty);

            // Crear el mensaje
            var message = MailHelper.CreateSingleEmail(from, toEmail, subject, plainTextContent, htmlContent);

            // Enviar el mensaje
            var response = await client.SendEmailAsync(message);

            // Manejar errores en caso de que el envío falle
            if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)
            {
                throw new Exception("Error: Solicitud inválida al enviar el correo.");
            }
            else if (!response.IsSuccessStatusCode)
            {
                var errorMessage = await response.Body.ReadAsStringAsync();
                throw new Exception($"Error al enviar el correo: {response.StatusCode} - {errorMessage}");
            }
        }
    }
}
