using Microsoft.EntityFrameworkCore;
using MTWorkHR.Core.Entities;
using MTWorkHR.Core.IDto;
using MTWorkHR.Infrastructure.Entities;
using MTWorkHR.Infrastructure.DBContext;
using MTWorkHR.Core.IRepositories;

namespace MTWorkHR.Infrastructure.Repositories
{
    public class ChatMessageRepository : Repository<ChatMessage>, IChatMessageRepository
    {
        private readonly DbSet<ChatMessage> dbSet;

        public ChatMessageRepository(HRDataContext context) : base(context)
        {
            dbSet = context.Set<ChatMessage>();
        }
        
        public async Task<ChatMessage> GetByIdWithAllChildren(long id)
        {
            return await dbSet
                .Include(x => x.ChatAttachments)
                .FirstOrDefaultAsync(x => x.Id == id);
        }
        public async Task<Tuple<IQueryable<ChatMessage>, int>> GetAllWithChildrenAsync(string userId, string contactId)
        {
            var query = dbSet.Include(x => x.ChatAttachments).Where(m=> (m.ReceiverId == contactId && m.SenderId == userId) || (m.ReceiverId == userId && m.SenderId == contactId)).AsQueryable();
            var total = await query.CountAsync();

            return new Tuple<IQueryable<ChatMessage>, int>(query, total);
        }

        public async Task<Tuple<IQueryable<ChatMessage>, int>> GetAllUserMessagesAsync(string userId)
        {
            var query = dbSet.Include(x => x.ChatAttachments).Where(m => (m.SenderId == userId) || (m.ReceiverId == userId )).AsQueryable();
            var total = await query.CountAsync();

            return new Tuple<IQueryable<ChatMessage>, int>(query, total);
        }
    }
}
