namespace Brizco.Repository.Handlers.ShiftPlans;

public class CreateShiftPlanCommandHandler : IRequestHandler<CreateShiftPlanCommand, ShiftPlanLDto>
{
    private readonly IRepositoryWrapper _repositoryWrapper;
    private readonly ICurrentUserService _currentUserService;

    public CreateShiftPlanCommandHandler(IRepositoryWrapper repositoryWrapper,ICurrentUserService currentUserService)
    {
        _repositoryWrapper = repositoryWrapper;
        _currentUserService = currentUserService;
    }
    public async Task<ShiftPlanLDto> Handle(CreateShiftPlanCommand request, CancellationToken cancellationToken)
    {
        var shift = await _repositoryWrapper.SetRepository<Shift>()
            .TableNoTracking
            .FirstOrDefaultAsync(s => s.Id == request.ShiftId, cancellationToken);
        if (shift == null)
            throw new AppException("Shift not found", ApiResultStatusCode.NotFound);
        var planFor = DateTimeExtensions.UnixTimeStampToDateTime(request.PlanDate);
        var existedShiftPlan = await _repositoryWrapper.SetRepository<ShiftPlan>()
            .TableNoTracking
            .FirstOrDefaultAsync(s => s.ShiftId == request.ShiftId && s.PlanFor.Date == planFor.Date, cancellationToken);

        if (existedShiftPlan != null)
            throw new AppException("Shift plan is exist for this date , you can update existed shift plan", ApiResultStatusCode.BadRequest);

        try
        {
            await _repositoryWrapper.BeginTransaction(cancellationToken);
            var shiftPlan = shift.AddPlan(planFor, request.RoutineId, request.SupervisionUserId);

            if (request.UserAndPositionIds.Count == 0)
                throw new AppException("شیفت بندی مورد نظر باید حداقل متشکل از یک فرد باشد", ApiResultStatusCode.BadRequest);


            foreach (var userAndPositionId in request.UserAndPositionIds)
            {
                shiftPlan.AddUser(userAndPositionId.Key, userAndPositionId.Value);
            }

            _repositoryWrapper.SetRepository<ShiftPlan>().Add(shiftPlan);
            await _repositoryWrapper.SaveChangesAsync(cancellationToken);
            await _repositoryWrapper.CommitAsync(cancellationToken);
            return shiftPlan.AdaptToLDto();
        }
        catch (Exception )
        {
            await _repositoryWrapper.RollBackAsync(cancellationToken);
            throw;
        }
    }
}