using MediatR;
using FacebookService.API.Application.Dtos;
using FacebookService.Domain.AggregatesModel.ConversationAggregate;

namespace FacebookService.API.Application.Queries;

/// <summary>
/// EN: Handler for GetConversationByIdQuery.
/// VI: Handler cho GetConversationByIdQuery.
/// </summary>
public class GetConversationByIdQueryHandler : IRequestHandler<GetConversationByIdQuery, ConversationDto?>
{
    private readonly IConversationRepository _conversationRepository;

    public GetConversationByIdQueryHandler(IConversationRepository conversationRepository)
    {
        _conversationRepository = conversationRepository ?? throw new ArgumentNullException(nameof(conversationRepository));
    }

    public async Task<ConversationDto?> Handle(
        GetConversationByIdQuery request,
        CancellationToken cancellationToken)
    {
        Conversation? conversation;

        if (request.IncludeMessages)
        {
            conversation = await _conversationRepository.GetByIdWithMessagesAsync(
                request.ConversationId, cancellationToken);
        }
        else
        {
            conversation = await _conversationRepository.GetByIdAsync(
                request.ConversationId, cancellationToken);
        }

        if (conversation is null)
        {
            return null;
        }

        return MapToDto(conversation, request.IncludeMessages);
    }

    private static ConversationDto MapToDto(Conversation conversation, bool includeMessages)
    {
        var messages = includeMessages 
            ? conversation.Messages.OrderBy(m => m.SentAt).Select(MapMessageToDto).ToList()
            : null;

        return new ConversationDto(
            conversation.Id,
            conversation.CustomerId,
            Customer: null, // EN: Not loaded here / VI: Không load ở đây
            conversation.PageId,
            conversation.Status.Name,
            conversation.Channel,
            conversation.AssignedAgentId,
            conversation.LastMessageAt,
            conversation.CreatedAt,
            messages
        );
    }

    private static MessageDto MapMessageToDto(Message message)
    {
        return new MessageDto(
            message.Id,
            message.SenderId,
            message.Content,
            message.MessageType.Name,
            message.Direction.Name,
            message.SentAt,
            message.FacebookMessageId,
            message.Metadata
        );
    }
}
