using Microsoft.EntityFrameworkCore;
using NetinaShop.Domain.Entities.Orders;

namespace NetinaShop.Repository.Handlers.Orders;

public class GetOrdersQueryHandler : IRequestHandler<GetOrdersQuery,List<OrderSDto>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetOrdersQueryHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    public async Task<List<OrderSDto>> Handle(GetOrdersQuery request, CancellationToken cancellationToken)
    {

        IQueryable<Order> orders = _repositoryWrapper.SetRepository<Order>()
            .TableNoTracking;

        if (request.DateFilter != null)
        {
            switch (request.DateFilter)
            {
                case OrderQueryDateFilter.CustomDate:
                    if (request.SelectedDate != null)
                        orders = orders.Where(o => o.CreatedAt.Date == DateTimeExtensions.UnixTimeStampToDateTime(request.SelectedDate.Value));
                    else
                        throw new AppException("For custom date you have to send SelectedDate",ApiResultStatusCode.BadRequest);
                    break;
                case OrderQueryDateFilter.ThisMonth:
                    orders = orders.Where(o => o.CreatedAt.Date >= new DateTime(DateTime.Today.Year,DateTime.Today.Month,1));
                    break;
                case OrderQueryDateFilter.ThisWeek:
                    orders = orders.Where(o => o.CreatedAt.Date >= DateTime.Today.AddDays(-7));
                    break;
                case OrderQueryDateFilter.Today:
                    orders = orders.Where(o => o.CreatedAt.Date == DateTime.Today.Date);
                    break;
                default:
                    break;
                
            }
        }

        if (request.OrderStatus != null)
            orders = orders.Where(o => o.OrderStatus == request.OrderStatus.Value);

        return await orders
            .OrderByDescending(o=>o.CreatedAt)
            .Skip(request.Page * 15)
            .Take(15)
            .Select(OrderMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);

    }
}