namespace Brizco.Core.QuartzServices.Handlers;

public class CreateShiftPlanNotificationsCommandHandler(IMediator mediator, IRepositoryWrapper repositoryWrapper)
    : IRequestHandler<CreateShiftPlanNotificationsCommand, bool>
{
    public async Task<bool> Handle(CreateShiftPlanNotificationsCommand request, CancellationToken cancellationToken)
    {
        if (request.InStart)
        {
            await mediator.Send(new SetShiftPlanNotificationScheduleCommand(request.ShiftPlanId), cancellationToken);
        }
        else
        {
            var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>().TableNoTracking
                .Where(s => s.Id == request.ShiftPlanId)
                .Select(ShiftPlanMapper.ProjectToSDto)
                .FirstOrDefaultAsync(cancellationToken);
            if (shiftPlan == null)
                throw new BaseApiException(ApiResultStatusCode.NotFound, "ShiftPlan not found in create shift plan notification");


            var shiftPlanUsers = await repositoryWrapper.SetRepository<ShiftPlanUser>()
            .TableNoTracking
                .Where(f => f.ShiftPlanId == request.ShiftPlanId)
                .ToListAsync(cancellationToken);

            foreach (var shiftPlanUser in shiftPlanUsers)
            {
                var completeShiftMessageForUser = $"شیفت‌های هفته بعد بسته شد، دیگه کار، کار، کار.";
                await mediator.Send(new CreateNotificationCommand(completeShiftMessageForUser, shiftPlanUser.UserId, shiftPlan.ComplexId), cancellationToken);
            }

        }
        return true;
    }
}