namespace Brizco.Repository.Handlers.Activities;

public class GetActivitiesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) 
    : IRequestHandler<GetActivitiesQuery, List<ActivitySDto>>
{
    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.Tasks.Activity> activities = repositoryWrapper.SetRepository<Domain.Entities.Tasks.Activity>().TableNoTracking
            .Where(a=>a.IsActivity && a.ComplexId == complexId);
        if (currentUserService is { Permissions: not null, RoleName: not null })
        {
            if (currentUserService.Permissions.Contains(ApplicationPermission.ViewMineActivities) && currentUserService.RoleName == ApplicationRoles.Staff)
                activities = activities.Where(a => a.UserId == userId);
            else
                activities = activities.Where(c => c.UserId == request.UserId);
        }

        if (request.DateQueryFilter != null)
        {
            var date = DateTime.Now;
            switch (request.DateQueryFilter)
            {
                case DateTimeQueryFilter.Yesterday:
                    activities = activities.Where(a => a.SetFor.Date == DateTime.Today.Date.AddDays(-1).Date);
                    break;
                case DateTimeQueryFilter.Today:
                    activities = activities.Where(a => a.SetFor.Date == DateTime.Today.Date);
                    break;
                case DateTimeQueryFilter.Tomorrow:
                    activities = activities.Where(a => a.SetFor.Date == DateTime.Today.AddDays(1).Date);
                    break;
                case DateTimeQueryFilter.ThisWeek:
                    DateTime today = DateTime.Today;
                    int delta = DayOfWeek.Saturday - today.DayOfWeek;
                    if (delta > 0) delta -= 7;
                    DateTime startOfWeek = today.AddDays(delta);
                    DateTime endOfWeek = startOfWeek.AddDays(6);
                    activities = activities.Where(a => a.SetFor.Date >= startOfWeek.Date && a.SetFor.Date <= endOfWeek.Date);
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

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

        if (request.SelectedShiftPlanId != default)
            activities = activities.Where(a => a.ShiftPlanId == request.SelectedShiftPlanId);


        var response= await activities.OrderByDescending(s => s.UserId)
            .Skip(request.Page * 20).Take(20)
            .Select(ActivityMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);
        return response;
    }
}