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

namespace CMSMicroservice.Application.DiscountShopCQ.Queries.GetUserOrders;

public class GetUserOrdersQueryHandler : IRequestHandler<GetUserOrdersQuery, GetUserOrdersResponseDto>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<GetUserOrdersResponseDto> Handle(GetUserOrdersQuery request, CancellationToken cancellationToken)
    {
        var query = _context.DiscountOrders
            .Where(o => o.UserId == request.UserId);

        // Apply filters
        if (request.PaymentStatus.HasValue)
        {
            query = query.Where(o => o.PaymentStatus == request.PaymentStatus.Value);
        }

        if (request.DeliveryStatus.HasValue)
        {
            query = query.Where(o => o.DeliveryStatus == request.DeliveryStatus.Value);
        }

        var totalCount = await query.CountAsync(cancellationToken);

        // Apply pagination
        var pagination = request.PaginationQuery ?? new PaginationState { PageNumber = 1, PageSize = 10 };

        var orders = await query
            .OrderByDescending(o => o.Created)
            .Skip((pagination.PageNumber - 1) * pagination.PageSize)
            .Take(pagination.PageSize)
            .Select(o => new OrderSummaryDto
            {
                Id = o.Id,
                TotalAmount = o.TotalAmount,
                DiscountBalanceUsed = o.DiscountBalanceUsed,
                GatewayAmountPaid = o.GatewayAmountPaid,
                VatAmount = o.VatAmount,
                PaymentStatus = o.PaymentStatus,
                PaymentDate = o.PaymentDate,
                DeliveryStatus = o.DeliveryStatus,
                TrackingCode = o.TrackingCode,
                Created = o.Created,
                ItemsCount = o.OrderDetails.Count
            })
            .ToListAsync(cancellationToken);

        return new GetUserOrdersResponseDto
        {
            MetaData = new MetaData
            {
                TotalCount = totalCount,
                PageSize = pagination.PageSize,
                CurrentPage = pagination.PageNumber,
                TotalPage = (int)Math.Ceiling(totalCount / (double)pagination.PageSize)
            },
            Models = orders
        };
    }
}
