module Gekanator
  class QuestionSuggestionPromoter
    def self.call(...) = new(...).call

    def initialize suggestion:, user:
      @suggestion = suggestion
      @user = user
    end

    def call
      suggestion.with_lock do
        return promoted_question if suggestion.processed?
        return suggestion if suggestion.answer == 'unknown'

        question = GekanatorQuestion.create!(
            text: suggestion.question_text,
            kind: 'post_similarity',
            source: 'user_suggested',
            status: 'accepted',
            priority_weight: 1.2,
            condition: {
              type: 'post-similarity',
              postId: suggestion.gekanator_game.correct_post_id,
              answer: suggestion.answer,
              threshold: 0.65
            },
            gekanator_question_suggestion: suggestion,
            created_by: user)
        example =
            GekanatorQuestionExample.new(
                gekanator_question: question,
                post: suggestion.gekanator_game.correct_post,
                user: user)
        example.record_answer!(
            answer: suggestion.answer,
            source: 'initial_suggestion',
            gekanator_game: suggestion.gekanator_game)
        example.save!
        suggestion.update!(processed: true)
        question
      end
    end

    private

    attr_reader :suggestion, :user

    def promoted_question
      suggestion.gekanator_questions.order(id: :desc).first
    end
  end
end
