class Player < ApplicationRecord
  # progress shape:
  # { "1" => { "answer_id" => 42, "result_id" => 99 }, "2" => { ... },
  #   "last_save" => { "answer_id" => 7 } }

  LAST_SAVE_KEY = "last_save".freeze

  SCORE_KEYS = %w[food_waste emissions income].freeze


  def record_answer(stage, answer_id)
    stage_data(stage)["answer_id"] = answer_id
    save
  end


  def add_to_score(overall:, impact: {})
    self.score = score.to_i + overall.to_i
    impact.each do |key, value|
      key = key.to_s
      next unless SCORE_KEYS.include?(key)
      scores[key] = scores[key].to_i + value.to_i
    end
    save
  end


  def score_for(key)
    scores[key.to_s].to_i
  end


  def record_result(stage, result_id)
    stage_data(stage)["result_id"] = result_id
    save
  end


  def answer_id_for(stage)
    progress[stage.to_s]&.dig("answer_id")
  end


  def result_id_for(stage)
    progress[stage.to_s]&.dig("result_id")
  end


  def record_last_save_answer(answer_id)
    stage_data(LAST_SAVE_KEY)["answer_id"] = answer_id
    save
  end


  def last_save_answer_id
    progress[LAST_SAVE_KEY]&.dig("answer_id")
  end


private


  def stage_data(stage)
    progress[stage.to_s] ||= {}
  end


end
