using Coravel.Invocable;
using Coravel.Mailer.Mail.Interfaces;
using EnotaryoPH.Data;
using EnotaryoPH.Web.Common.Models;
using EnotaryoPH.Web.Mailables;

namespace EnotaryoPH.Web.Common.Jobs
{
    public class SignatoryInvitationInvocable : IInvocable, IInvocableWithPayload<Guid>
    {
        private readonly IMailer _mailer;
        private readonly NotaryoDBContext _notaryoDBContext;
        private readonly Settings _settings;

        public SignatoryInvitationInvocable(IMailer mailer, NotaryoDBContext notaryoDBContext, Settings settings)
        {
            _mailer = mailer;
            _notaryoDBContext = notaryoDBContext;
            _settings = settings;
        }

        public Guid Payload { get; set; }

        public async Task Invoke()
        {
            var signatory = _notaryoDBContext
                .TransactionSignatories
                .Include(e => e.Transaction)
                .ThenInclude(t => t.Principal)
                .FirstOrDefault(e => e.TransactionSignatory_UID == Payload);

            var user = signatory.Transaction.Principal;
            var name = $"{user.Firstname} {user.Lastname}".NullIfWhiteSpace() ?? user.Email;
            var invitationCode = new Guid(signatory.InvitationCode).ToBase64String();

            await _mailer.SendAsync(new SignatoryInvitationMailable(new SignatoryViewModel
            {
                Email = signatory.Email,
                InvitationURL = $"{_settings.BaseUrl}/Participant/Registration/{invitationCode}",
                MainPrincipalName = name,
                SignatoryType = signatory.Type
            }));

            signatory.Status = nameof(SignatoryStatus.EmailSent);
            _notaryoDBContext.TransactionSignatories.Update(signatory);
            _notaryoDBContext.SaveChanges();
        }
    }
}