using Microsoft.EntityFrameworkCore;
using TIAM.Entities.Emails;
using TIAM.Entities.Products;

namespace TIAM.Database.DbSets.Emails;

public static class EmailMessageDbSetExtension
{
    public static EmailMessage? GetEmailMessageById(this IEmailMessageDbSet ctx, Guid emailMessageId)
        => ctx.EmailMessages.FirstOrDefault(x => x.Id == emailMessageId);

    public static IQueryable<EmailMessage> GetEmailMessagesByContextId(this IEmailMessageDbSet ctx, Guid contextId)
        => ctx.EmailMessages.Where(x => x.ContextId == contextId);

    public static IQueryable<EmailMessage> GetEmailMessagesBySenderId(this IEmailMessageDbSet ctx, Guid senderId)
        => ctx.EmailMessages.Where(x => x.SenderId == senderId);

    public static IQueryable<EmailMessage> GetEmailMessagesBySenderEmailAddress(this IEmailMessageDbSet ctx, string senderEmailAddress)
        => ctx.EmailMessages.Where(x => x.SenderEmailAddress == senderEmailAddress);

    private static IQueryable<EmailMessage> GetEmailMessages(this IQueryable<EmailMessage> queryableEmails, Guid userId, Guid userProductMappingId)
        => queryableEmails.Where(x => x.SenderId == userId || x.SenderId == userProductMappingId || x.Recipients.Any(recipient => recipient.RecipientId == userId || recipient.RecipientId == userProductMappingId));

    public static IQueryable<EmailMessage> GetEmailMessages(this IEmailMessageDbSet ctx, Guid userId, Guid userProductMappingId)
        => ctx.EmailMessages.GetEmailMessages(userId, userProductMappingId);

    public static IQueryable<EmailMessage> GetEmailMessages(this IEmailMessageDbSet ctx, Guid contextId, Guid userId, Guid userProductMappingId)
        => ctx.GetEmailMessagesByContextId(contextId).GetEmailMessages(userId, userProductMappingId);

    #region Add, Update, Remove

    public static bool AddEmailMessage(this IEmailMessageDbSet ctx, EmailMessage emailMessage)
        => ctx.EmailMessages.Add(emailMessage).State == EntityState.Added;

    public static bool UpdateEmailMessage(this IEmailMessageDbSet ctx, EmailMessage emailMessage)
        => ctx.EmailMessages.Update(emailMessage).State == EntityState.Modified;

    public static bool RemoveEmailMessage(this IEmailMessageDbSet ctx, Guid emailMessageId)
    {
        var emailMessage = ctx.GetEmailMessageById(emailMessageId);

        return emailMessage == null || ctx.RemoveEmailMessage(emailMessage);
    }

    public static bool RemoveEmailMessage(this IEmailMessageDbSet ctx, EmailMessage emailMessage)
        => ctx.EmailMessages.Remove(emailMessage).State == EntityState.Deleted;

    #endregion Add, Update, Remove

}