using MessageService.Domain.Entities; using MessageService.Domain.IReposities; using MessageService.Domain.Models; using Microsoft.EntityFrameworkCore; namespace MessageService.Infrastructure.Reposities { public class ConversationReposity : IConversationReposity { private readonly MessageDbContext db; public ConversationReposity(MessageDbContext db) { this.db = db; } public void Create(Conversation conversation) { db.Conversations.Add(conversation); } public async Task> FindAllStreamKeyAsync(Guid userId, CancellationToken cancellationToken = default) { return await db.Conversations.Where(x => x.UserId == userId) .AsNoTracking() .Select(s => s.StreamKey) .ToListAsync(cancellationToken); } public async Task FindByIdAsync(Guid id, CancellationToken cancellationToken = default) { return await db.Conversations.FirstOrDefaultAsync(x => x.Id == id, cancellationToken); } public async Task> FindByStreamKeyAsync(string streamKey, CancellationToken cancellationToken = default) { return await db.Conversations.Where(x => x.StreamKey == streamKey).ToListAsync(cancellationToken); } public async Task> FindByTargetIdAsync(Guid targetId, CancellationToken cancellationToken = default) { return await db.Conversations.Where(x => x.TargetId == targetId).ToListAsync(cancellationToken); } public async Task> ListByUserIdAsync(Guid userId, CancellationToken cancellationToken = default) { return await db.Conversations .AsNoTracking() .Where(x => x.UserId == userId) .OrderByDescending(x => x.LastMessageTime ?? x.CreationTime) .Select(x => new ConversationSummary( x.Id, x.UserId, x.TargetId, x.TargetAvatar, x.TargetName, x.LastReadSequenceId, x.UnreadCount, x.ChatType, x.LastMessage, x.LastMessageTime ?? x.CreationTime)) .ToListAsync(cancellationToken); } public Task FindActiveAsync(Guid userId, Guid targetId, Domain.Enums.ChatType chatType, CancellationToken cancellationToken = default) { return db.Conversations.FirstOrDefaultAsync( x => x.UserId == userId && x.TargetId == targetId && x.ChatType == chatType, cancellationToken); } } }