namespace Brizco.Repository.Handlers.Routines;

public class GetRoutineShiftsQueryHandler : IRequestHandler<GetRoutineShiftsQuery,List<RoutineShiftResponseDto>>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public GetRoutineShiftsQueryHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }

    public async Task<List<RoutineShiftResponseDto>> Handle(GetRoutineShiftsQuery request, CancellationToken cancellationToken)
    {
        var routineShiftResponse = new List<RoutineShiftResponseDto>();

        var shiftRoutines = await _repositoryWrapper.SetRepository<ShiftRoutine>()
            .TableNoTracking
            .Where(s => s.RoutineId == request.Id)
            .ToListAsync(cancellationToken);
        foreach (var shiftRoutine in shiftRoutines)
        {
            var shift = await _repositoryWrapper.SetRepository<Shift>()
                .TableNoTracking
                .Where(s => s.Id == shiftRoutine.ShiftId)
                .Select(ShiftMapper.ProjectToSDto)
                .FirstOrDefaultAsync(cancellationToken);
            if (shift == null)
                continue;
            shift.Days.ForEach(d =>
            {
                var routineShiftRes = routineShiftResponse.FirstOrDefault(s => s.Day == d);
                if (routineShiftRes != null)
                {
                    routineShiftRes.Shifts.Add(shift);
                }
                else
                {
                    routineShiftResponse.Add(new RoutineShiftResponseDto
                    {
                        Shifts = new List<ShiftSDto>{shift},
                        Day = d
                    });
                }
            });
            if (request.SelectedDate > 0)
            {
                var selectedDate = DateTimeExtensions.UnixTimeStampToDateTime(request.SelectedDate);

                var existedShiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>()
                    .TableNoTracking
                    .FirstOrDefaultAsync(s => s.ShiftId == shift.Id && s.PlanFor.Date == selectedDate.Date, cancellationToken);
                shift.IsCompleted = existedShiftPlan?.IsCompleted ?? false;
                shift.CurrentShiftPlanId = existedShiftPlan?.Id ?? default;
                shift.HasCurrentShiftPlan = existedShiftPlan != null;
            }
            
        }

        return routineShiftResponse;
    }
}