public bool Valid(HabitGoal goal)
        {
            if (!_goalValidator.Valid(goal))
            {
                return(false);
            }

            return(goal.Target > 0 && goal.Logs.All(log => log.Date >= goal.StartDate && log.Date <= goal.EndDate));
        }
        public string GetInvalidMessage(HabitGoal goal)
        {
            var goalInvalidMessage = _goalValidator.GetInvalidMessage(goal);

            if (!string.IsNullOrEmpty(goalInvalidMessage))
            {
                return(goalInvalidMessage);
            }

            return(goal.Target <= 0 ? "Target must be greater than 0." : "Logs must be between the goal start and end date.");
        }
        public IActionResult Post([FromBody] HabitGoal value)
        {
            if (!_validator.Valid(value))
            {
                return(BadRequest(_validator.GetInvalidMessage(value)));
            }

            var goal = _context.HabitGoals.Add(value).Entity;

            _context.SaveChanges();

            return(Ok(goal));
        }
        public IActionResult Put([FromRoute] int id, [FromBody] HabitGoal value)
        {
            if (!_validator.Valid(value))
            {
                return(BadRequest(_validator.GetInvalidMessage(value)));
            }

            var habitToUpdate = _context.HabitGoals.Include(g => g.Logs).Single(g => g.HabitGoalId == id);

            if (habitToUpdate == null)
            {
                return(NotFound());
            }

            habitToUpdate.Name      = value.Name;
            habitToUpdate.Target    = value.Target;
            habitToUpdate.StartDate = value.StartDate;
            foreach (var log in value.Logs)
            {
                if (habitToUpdate.Logs.Any(i => i.HabitLogId == log.HabitLogId))
                {
                    var logToUpdate = habitToUpdate.Logs.Single(i => i.HabitLogId == log.HabitLogId);
                    logToUpdate.Date           = log.Date;
                    logToUpdate.HabitCompleted = log.HabitCompleted;
                    _context.HabitLogs.Update(logToUpdate);
                }
                else
                {
                    _context.HabitLogs.Add(log);
                }
            }

            var goal = _context.HabitGoals.Update(habitToUpdate).Entity;

            _context.SaveChanges();
            return(Ok(goal));
        }