using CMSMicroservice.Application.Common.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace CMSMicroservice.Application.DiscountShopCQ.Queries.GetOrderById;

public class GetOrderByIdQueryHandler : IRequestHandler<GetOrderByIdQuery, OrderDetailDto?>
{
    private readonly IApplicationDbContext _context;

    public GetOrderByIdQueryHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<OrderDetailDto?> Handle(GetOrderByIdQuery request, CancellationToken cancellationToken)
    {
        var query = _context.DiscountOrders
            .Where(o => o.Id == request.OrderId);

        if (request.UserId.HasValue && request.UserId.Value > 0)
        {
            query = query.Where(o => o.UserId == request.UserId.Value);
        }

        var order = await query
            .Include(o => o.UserAddress)
            .Include(o => o.User)
            .Include(o => o.OrderDetails)
                .ThenInclude(od => od.Product)
            .FirstOrDefaultAsync(cancellationToken);

        if (order == null)
            return null;

        return new OrderDetailDto
        {
            Id = order.Id,
            UserId = order.UserId,
            TotalAmount = order.TotalAmount,
            DiscountBalanceUsed = order.DiscountBalanceUsed,
            GatewayAmountPaid = order.GatewayAmountPaid,
            VatAmount = order.VatAmount,
            PaymentStatus = order.PaymentStatus,
            PaymentDate = order.PaymentDate,
            DeliveryStatus = order.DeliveryStatus,
            TrackingCode = order.TrackingCode,
            DeliveryDescription = order.DeliveryDescription,
            Created = order.Created,
            Address = new UserAddressDto
            {
                Title = order.UserAddress.Title,
                Address = order.UserAddress.Address,
                PostalCode = order.UserAddress.PostalCode,
                Phone = order.User?.Mobile
            },
            Items = order.OrderDetails.Select(od => new OrderItemDto
            {
                ProductId = od.ProductId,
                ProductTitle = od.Product.Title,
                Count = od.Count,
                UnitPrice = od.UnitPrice,
                DiscountPercentUsed = od.DiscountPercentUsed,
                DiscountAmount = od.DiscountAmount,
                FinalPrice = od.FinalPrice,
                ImagePath = od.Product.ImagePath ?? "",
                ThumbnailPath = od.Product.ThumbnailPath ?? ""
            }).ToList()
        };
    }
}
