using MediatR;
using MktZaloService.Domain.AggregatesModel.ConversationAggregate;

namespace MktZaloService.API.Application.Queries.Conversations;

/// <summary>
/// EN: Handler for GetConversationHistoryQuery.
/// VI: Handler cho GetConversationHistoryQuery.
/// </summary>
public class GetConversationHistoryQueryHandler 
    : IRequestHandler<GetConversationHistoryQuery, ConversationHistoryDto?>
{
    private readonly IConversationRepository _conversationRepository;

    public GetConversationHistoryQueryHandler(IConversationRepository conversationRepository)
    {
        _conversationRepository = conversationRepository;
    }

    public async Task<ConversationHistoryDto?> Handle(
        GetConversationHistoryQuery request,
        CancellationToken cancellationToken)
    {
        var conversation = await _conversationRepository.GetByIdWithMessagesAsync(
            request.ConversationId,
            request.Skip,
            request.Take,
            cancellationToken);

        if (conversation == null)
        {
            return null;
        }

        return new ConversationHistoryDto(
            conversation.Id,
            conversation.ZaloUserId,
            conversation.CustomerId,
            conversation.Status.ToString(),
            conversation.MessageCount,
            conversation.StartedAt,
            conversation.LastMessageAt ?? conversation.StartedAt,
            conversation.Messages
                .OrderByDescending(m => m.SentAt)
                .Select(m => new MessageDto(
                    m.Id,
                    m.Type.ToString(),
                    m.Content,
                    m.Direction.ToString(),
                    m.IsFromBot,
                    m.SentAt,
                    m.ZaloMessageId))
                .ToList());
    }
}
