using System;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using TwilioSMSReceiver.Common.Interfaces;
using TwilioSMSReceiver.Data.Models;

namespace TwilioSMSReceiver.Common.MessageHandlers
{
	public class GraphSmtpHandler : IMessageHandler
	{
        protected readonly ILogger _logger;
        protected readonly IConfiguration _configuration;

        protected GraphServiceClient BuildGraphClient()
        {
            var section = _configuration.GetSection("GraphSmtp");
            var tenantId = section["tenantId"];
            var appId = section["appId"];
            var secret = section["secret"];
            var scopes = new[] { "https://graph.microsoft.com/.default" };

            var options = new TokenCredentialOptions
            {
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
            };

            var clientSecretCredential = new ClientSecretCredential(
                tenantId, appId, secret, options);

            return new GraphServiceClient(clientSecretCredential, scopes);
        }

        public GraphSmtpHandler(ILogger logger, IConfiguration configuration)
		{
            _configuration = configuration;
            _logger = logger;
		}

        public async Task<bool> RelaySms(SMSModel model)
        {
            try
            {
                var graphClient = BuildGraphClient();
                var message = new Message
                {
                    Subject = $"Received SMS from {model.SenderNumber} to {model.SenderNumber}",
                    Body = new ItemBody
                    {
                        ContentType = BodyType.Text,
                        Content = model.MessageContents
                    },
                    ToRecipients = new List<Recipient>()
    {
        new Recipient
        {
            EmailAddress = new EmailAddress
            {
                Address = _configuration.GetSection("GraphSmtp")["destEmail"]
            }
        }
    }
                };

                await graphClient.Me.SendMail(message).Request().PostAsync();

                return true;
            }
            catch (Exception e)
            {
                _logger.LogWarning($"Error occured {e}");
            }
            return false;
        }
    }
}

