// EN: Handler for GetOrderReturnsQuery.
// VI: Handler cho GetOrderReturnsQuery.

using MediatR;
using OrderService.API.Application.DTOs;
using OrderService.Domain.AggregatesModel.OrderAggregate;

namespace OrderService.API.Application.Queries;

/// <summary>
/// EN: Handler for querying return history of an order.
/// VI: Handler cho query lịch sử trả hàng của đơn hàng.
/// </summary>
public class GetOrderReturnsQueryHandler : IRequestHandler<GetOrderReturnsQuery, List<ReturnOrderDto>>
{
    private readonly IOrderRepository _orderRepository;
    private readonly ILogger<GetOrderReturnsQueryHandler> _logger;

    public GetOrderReturnsQueryHandler(
        IOrderRepository orderRepository,
        ILogger<GetOrderReturnsQueryHandler> logger)
    {
        _orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository));
        _logger = logger ?? throw new ArgumentNullException(nameof(logger));
    }

    public async Task<List<ReturnOrderDto>> Handle(GetOrderReturnsQuery request, CancellationToken cancellationToken)
    {
        _logger.LogInformation(
            "EN: Getting return history for order {OrderId} / VI: Lấy lịch sử trả hàng cho đơn {OrderId}",
            request.OrderId);

        var returns = await _orderRepository.GetReturnsByOriginalOrderIdAsync(
            request.OrderId, cancellationToken);

        return returns.Select(r => new ReturnOrderDto(
            r.Id,
            request.OrderId,
            r.ReturnReason ?? string.Empty,
            r.TotalAmount,
            r.Status.Name,
            r.ReturnedAt ?? r.CreatedAt,
            r.Items.Select(i => new OrderItemDto(
                i.Id,
                i.ProductId,
                i.ProductName,
                i.ProductType,
                i.Quantity,
                i.UnitPrice,
                i.TotalPrice,
                i.Status)).ToList()
        )).ToList();
    }
}
