#nullable disable
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TwilioSMSReceiver.Common.Interfaces;
using TwilioSMSReceiver.Data;
using TwilioSMSReceiver.Data.Models;

namespace TwilioSMSReceiver.Common.MessageHandlers
{
    public abstract class BaseHandler : IMessageHandler
    {
        protected readonly SMSDbCtx sMSDbCtx;
        protected readonly ILogger<BaseHandler> _logger;
        protected readonly IServiceProvider _serviceProvider;

        public BaseHandler(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
            sMSDbCtx = _serviceProvider.CreateScope().ServiceProvider.GetService<SMSDbCtx>();
            _logger = _serviceProvider.CreateScope().ServiceProvider.GetService<ILogger<BaseHandler>>();
        }
        public virtual async Task<bool> RelaySms(SMSModel model)
        {
            if (sMSDbCtx.SMSMessages.Any(b => b.Id == model.Id))
            {
                var message =
                    sMSDbCtx.SMSMessages.Where(b => b.Id == model.Id).First();
                if (!message.IsForwardedYet)
                {
                    _logger.LogInformation($"Marking message with id {message.Id} as forwarded");
                    message.IsForwardedYet = true;
                    sMSDbCtx.SMSMessages.Update(message);
                    await sMSDbCtx.SaveChangesAsync();
                    await sMSDbCtx.DisposeAsync();
                    return true;
                }
            }
            await sMSDbCtx.DisposeAsync();
            return false;
        }
    }
}
