using SecureSharing.Business.Interfaces;
using SecureSharing.Models;

namespace SecureSharing.Infrastructure;

public sealed class ModelFactory : IModelFactory
{
    private readonly IMessageService _messageService;

    public ModelFactory(IMessageService messageService)
    {
        _messageService = messageService;
    }

    public async Task<LinkModel> PrepareLinkVM(Guid code, bool? share)
    {
        //share is true when the link is created

        LinkModel model = null;
        try
        {
            var message = await _messageService.GetByCode(code);

            model = new LinkModel
            {
                MessageModel = new MessageModel { Code = code, Text = message.Text }, Share = share,
                IsValid = message.IsValid
            };

            if (model.IsValid)
            {
                if (message.ExpiryDate != null)
                {
                    model.TimeLeft = message.ExpiryDate - DateTime.UtcNow;
                    if (message.ExpiryDate <= DateTime.UtcNow)
                    {
                        await _messageService.InvalidateMessage(message.Id);
                        model.IsValid = false;
                    }
                }
                else
                {
                    //ONE_TIME sharing: make the message invalid now so that it can't be accessed next time
                    if (share is null or false) await _messageService.InvalidateMessage(message.Id);
                }
            }
        }
        catch (Exception _)
        {
            model = new LinkModel { IsValid = false };
        }

        return model;
    }

    //public MessageModel PrepareMessageVM(MessageDto message)
    //{
    //    throw new System.NotImplementedException();
    //}
}