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)
        {
            _apiKey = configuration["SendGrid:ApiKey"];
            _fromEmail = configuration["SendGrid:FromEmail"];
            _fromName = configuration["SendGrid:FromName"];
        }

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

            var from = new EmailAddress(_fromEmail, _fromName);
            var toEmail = new EmailAddress(to);

            var plainTextContent = System.Text.RegularExpressions.Regex.Replace(htmlContent, "<[^>]+>", string.Empty);

            var message = MailHelper.CreateSingleEmail(from, toEmail, subject, plainTextContent, htmlContent);

            var response = await client.SendEmailAsync(message);

            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}");
            }
        }
    }
}
