class GekanatorQuestionSuggestionsController < ApplicationController
  def create
    return head :unauthorized unless current_user

    game = GekanatorGame.find_by(id: params.require(:gekanator_game_id))
    return head :not_found unless game
    if !current_user.admin? && game.user_id != current_user.id
      return head :not_found
    end

    existing_question_id = params[:existing_question_id].presence
    if existing_question_id
      question = GekanatorQuestion.accepted.find_by(id: existing_question_id)
      return head :not_found unless question
      unless learnable_existing_question?(question)
        return render_validation_error fields: { existing_question_id: ['質問が不正です．'] }
      end

      example =
          GekanatorQuestionExample.find_or_initialize_by(
              gekanator_question: question,
              post: game.correct_post,
              user: current_user)
      example.record_answer!(
          answer: params.require(:answer),
          source: 'post_game_extra',
          gekanator_game: game)

      if example.save
        render json: {
          id: question.id,
          count: game.question_suggestions.count
        }, status: :created
      else
        render_validation_error example
      end
      return
    end

    suggestion = GekanatorQuestionSuggestion.new(
        gekanator_game: game,
        user: current_user,
        question_text: params.require(:question_text),
        answer: params.require(:answer))

    if suggestion.valid?
      ActiveRecord::Base.transaction do
        suggestion.save!
        Gekanator::QuestionSuggestionPromoter.call(
            suggestion: suggestion,
            user: current_user)
      end

      render json: {
        id: suggestion.id,
        count: game.question_suggestions.count
      }, status: :created
    else
      render_validation_error suggestion
    end
  end

  def ai_convert
    return head :not_found unless current_user&.admin?

    suggestion = GekanatorQuestionSuggestion.find_by(id: params[:id])
    return head :not_found unless suggestion
    if Gekanator::AiRunBudget.exceeded_after_next_run?
      suggestion.gekanator_ai_runs.create!(
          model: 'budget_guard',
          status: 'blocked_budget',
          input_tokens: 0,
          output_tokens: 0,
          estimated_cost_jpy: 0)
      return head :payment_required
    end

    Gekanator::QuestionSuggestionAiConverter.call(
        suggestion: suggestion,
        user: current_user)
    head :no_content
  rescue NotImplementedError
    head :not_implemented
  end

  private

  def learnable_existing_question? question
    return true if question.kind == 'post_similarity'
    return false unless question.kind == 'tag'

    key = question.condition.as_json['key'].to_s
    !key.start_with?('nico:')
  end
end
