# frozen_string_literal: true

module Answerly
  module Admin
    class SectionTemplate < ApplicationRecord
      self.table_name = 'answerly_section_templates'

      belongs_to :template, class_name: '::Answerly::Admin::SurveyTemplate', inverse_of: :sections, foreign_key: :answerly_survey_template_id
      has_many :questions, class_name: '::Answerly::Admin::QuestionTemplate', inverse_of: :section, foreign_key: :answerly_section_template_id, dependent: :destroy

      accepts_nested_attributes_for :questions, allow_destroy: true
  
      scope :get_by_order, -> { order(order: :asc) }

      before_create :assign_order

      # # TODO: add more validation
      validates_presence_of :title

      def ordered_questions
        questions.get_by_order
      end

      def reorder_questions(questions_ids: [])
        questions_ids.each_with_index do |question_id, index|
          question = questions.find_by(id: question_id)
          question&.update(order: index)
        end
      end

      def update_question(question_id, params = {})
        questions.where(id: question_id).update(params)
      end

      def destroy_question(question_id)
        questions.destroy(question_id)
      end

      def create_question(params = {})
        questions.create(params)
      end

      def build_question(params = {})
        questions.build(params)
      end

      private

      def assign_order
        self.order = template.sections.size if self.order.nil?
      end
    end
  end
end
