using Brizco.Domain.Entities.Shift;

namespace Brizco.Repository.Handlers.ShiftPlan;

public class GetShiftPlansQueryHandler : IRequestHandler<GetShiftPlansQuery, List<ShiftPlanSDto>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;

    public GetShiftPlansQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService)
    {
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
    }
    public async Task<List<ShiftPlanSDto>> Handle(GetShiftPlansQuery request, CancellationToken cancellationToken)
    {
        List<ShiftPlanSDto> shiftPlans;
        if (request.SelectedDate > 0)
        {
            var selectedDate = DateTimeExtensions.UnixTimeStampToDateTime(request.SelectedDate);
            shiftPlans = await _repositoryWrapper.SetRepository<Domain.Entities.Shift.ShiftPlan>()
                .TableNoTracking
                .Where(s => s.PlanFor.Date == selectedDate.Date)
                .OrderByDescending(s => s.CreatedAt)
                .Skip(request.Page * 15).Take(15)
                .Select(ShiftPlanMapper.ProjectToSDto)
                .ToListAsync(cancellationToken);
            foreach (var shiftPlan in shiftPlans)
            {
                var activitiesCount = await _repositoryWrapper.SetRepository<Domain.Entities.Task.Activity>()
                    .TableNoTracking
                    .CountAsync(a => a.SetFor.Date == selectedDate.Date && a.ShiftId == shiftPlan.Id, cancellationToken);
                var doneActivitiesCount = await _repositoryWrapper.SetRepository<Domain.Entities.Task.Activity>()
                    .TableNoTracking
                    .CountAsync(a => a.Status == ActivityStatus.Done && a.SetFor.Date == selectedDate.Date && a.ShiftId == shiftPlan.Id, cancellationToken);
                var undoneActivitiesCount = await _repositoryWrapper.SetRepository<Domain.Entities.Task.Activity>()
                    .TableNoTracking
                    .CountAsync(a => a.Status == ActivityStatus.UnDone && a.SetFor.Date == selectedDate.Date && a.ShiftId == shiftPlan.Id, cancellationToken);
                shiftPlan.UndoneActivitiesCount = undoneActivitiesCount;
                shiftPlan.DoneActivitiesCount = doneActivitiesCount;
                shiftPlan.TotalActivitiesCount = activitiesCount;
            }

        }
        else
        {
            shiftPlans = await _repositoryWrapper.SetRepository<Domain.Entities.Shift.ShiftPlan>().TableNoTracking
                .OrderByDescending(s => s.CreatedAt)
                .Skip(request.Page * 15).Take(15)
                .Select(ShiftPlanMapper.ProjectToSDto)
                .ToListAsync(cancellationToken);
        }

        return shiftPlans;
    }
}