using TwilioSMSReceiver.Data.Models;
using TeamsHook.NET;
using Microsoft.Extensions.Logging;
using TwilioSMSReceiver.Common.MessageHandlers;

namespace TwilioSMSReceiver.Common.Handlers
{
    public class MSTeamsHandler : BaseHandler
    {
        public MSTeamsHandler(IServiceProvider serviceProvider) : base(serviceProvider)
        {
        }

        public override async Task<bool> RelaySms(SMSModel model)
        {
            var teams = sMSDbCtx.MSTeamsWebHooks;
            if (!teams.Any())
            {
                _logger.LogWarning("Teams Webhook list is empty!");
                return false;
            }
            List<Task> teamsPostRequests = new List<Task>();
            foreach (var teamHook in teams)
            {
                try
                {
                    var teamsClient = new TeamsHookClient();
                    var card = new MessageCard
                    {
                        Title = $"Incoming SMS from {model.SenderNumber}",
                        Summary = $"Sent to {model.ReceivedNumber}",
                        Text = $"{model.MessageContents}"
                    };

                    teamsPostRequests.Add(teamsClient.PostAsync(teamHook.WebHookUri, card));
                } catch (Exception ex)
                {
                    _logger.LogError($"Webhook with URL {teamHook.WebHookUri} failed to post. Exception here {ex}");
                }
            }

            try
            {
                await Task.WhenAll(teamsPostRequests);
            } catch (Exception ex)
            {
                _logger.LogError($"Webhook failure {ex}");
            }

            return await base.RelaySms(model);
        }
    }
}
