namespace Brizco.Repository.Handlers.Activity;

public class GetActivitiesQueryHandler : IRequestHandler<GetActivitiesQuery, List<ActivitySDto>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;

    public GetActivitiesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
    {
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
    }
    public async Task<List<ActivitySDto>> Handle(GetActivitiesQuery request, CancellationToken cancellationToken)
    {
        if (_currentUserService.ComplexId == null)
            throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
        if (!Guid.TryParse(_currentUserService.ComplexId, out Guid complexId))
            throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);

        if (_currentUserService.UserId == null)
            throw new AppException("UserId is null", ApiResultStatusCode.NotFound);
        if (!Guid.TryParse(_currentUserService.UserId, out Guid userId))
            throw new AppException("UserId is wrong", ApiResultStatusCode.NotFound);


        IQueryable<Domain.Entities.Task.Activity> activities = _repositoryWrapper.SetRepository<Domain.Entities.Task.Activity>().TableNoTracking
            .Where(a=>a.IsActivity);

        if (request.DateQueryFilter != null)
        {
            switch (request.DateQueryFilter)
            {
                case DateQueryFilter.Today:
                    activities = activities.Where(a => a.SetFor.Date == DateTime.Today.Date);
                    break;
                case DateQueryFilter.Tomorrow:
                    activities = activities.Where(a => a.SetFor.Date == DateTime.Today.AddDays(1).Date);
                    break;
                case DateQueryFilter.ThisWeek:
                    activities = activities.Where(a => a.SetFor.Date >= DateTime.Today.AddDays(-1).Date && a.SetFor.Date <= DateTime.Today.AddDays(+6).Date);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        if (request.SelectedDate > 0)
        {
            var selectedDate = DateTimeExtensions.UnixTimeStampToDateTime(request.SelectedDate);
            activities = activities.Where(a => a.ComplexId == complexId && a.SetFor.Date == selectedDate.Date);
        }

        if (request.SelectedShift != default)
            activities = activities.Where(a => a.ComplexId == complexId && a.ShiftId == request.SelectedShift);

        if (request.SelectedDate == 0 && request.SelectedShift == default)
            activities = activities.Where(a => a.UserId == userId);



        return await activities.OrderBy(s => s.ScheduleType)
            .Skip(request.Page * 15).Take(15)
            .Select(ActivityMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);
    }
}