namespace CMSMicroservice.Application.UserOrderCQ.Queries.GetUserOrder;
public class GetUserOrderQueryHandler : IRequestHandler<GetUserOrderQuery, GetUserOrderResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetUserOrderResponseDto> Handle(GetUserOrderQuery request,
        CancellationToken cancellationToken)
    {
        var response = await _context.UserOrders
            .Include(i => i.UserAddress)
            .Include(i => i.User)
            .Include(i => i.FactorDetails)
                .ThenInclude(t => t.Product)
            .Include(i => i.OrderVAT)
            .AsNoTracking()
            .Where(x => x.Id == request.Id)
            .Select(x => new GetUserOrderResponseDto
            {
                Id = x.Id,
                Amount = x.Amount,
                PackageId = x.PackageId ?? 0,
                TransactionId = x.TransactionId,
                PaymentStatus = x.PaymentStatus,
                PaymentDate = x.PaymentDate,
                UserId = x.UserId,
                UserAddressId = x.UserAddressId,
                PaymentMethod = x.PaymentMethod,
                UserAddressText = x.UserAddress.Address,
                FactorDetails = x.FactorDetails.Select(fd => new GetUserOrderResponseFactorDetail
                {
                    ProductId = fd.ProductId,
                    ProductTitle = fd.Product.Title,
                    ProductThumbnailPath = fd.Product.ThumbnailPath,
                    UnitPrice = fd.UnitPrice,
                    Count = fd.Count,
                    UnitDiscountPrice = fd.UnitDiscountPrice
                }).ToList(),
                DeliveryStatus = x.DeliveryStatus,
                TrackingCode = x.TrackingCode,
                DeliveryDescription = x.DeliveryDescription,
                UserFullName = (x.User.FirstName ?? string.Empty) + " " + (x.User.LastName ?? string.Empty),
                UserNationalCode = x.User.NationalCode,
                VatInfo = x.OrderVAT != null ? new OrderVATInfoDto
                {
                    VatRate = x.OrderVAT.VATRate,
                    BaseAmount = x.OrderVAT.BaseAmount,
                    VatAmount = x.OrderVAT.VATAmount,
                    TotalAmount = x.OrderVAT.TotalAmount,
                    IsPaid = x.OrderVAT.IsPaid
                } : null
            })
            .FirstOrDefaultAsync(cancellationToken);

        return response ?? throw new NotFoundException(nameof(UserOrder), request.Id);
    }
}
