# frozen_string_literal: true

class UxToolkitChecklistTemplateItem < ApplicationRecord
  belongs_to :checklist_template,
             class_name: 'UxToolkitChecklistTemplate',
             inverse_of: :items

  validates :checklist_template_id, presence: true
  validates :subject, presence: true, length: {maximum: 255}
  validates :position, presence: true, numericality: {only_integer: true, greater_than_or_equal_to: 1}

  scope :ordered, -> { order(:position, :id) }

  def self.next_position_for(template)
    where(checklist_template_id: template.id).maximum(:position).to_i + 1
  end

  def self.normalize_positions_for(template)
    where(checklist_template_id: template.id).ordered.each_with_index do |item, index|
      next_position = index + 1
      item.update_column(:position, next_position) if item.position != next_position
    end
  end

  def move_up
    swap_with(sibling_at(position.to_i - 1))
  end

  def move_down
    swap_with(sibling_at(position.to_i + 1))
  end

  private

  def sibling_at(next_position)
    return nil if next_position < 1

    self.class.where(checklist_template_id: checklist_template_id, position: next_position).first
  end

  def swap_with(other)
    return false unless other

    current_position = position
    transaction do
      update_column(:position, other.position)
      other.update_column(:position, current_position)
    end
    true
  end
end
