# frozen_string_literal: true

class UxToolkitChecklistItem < ApplicationRecord
  belongs_to :issue, optional: true
  belongs_to :created_by, class_name: 'User', optional: true
  belongs_to :updated_by, class_name: 'User', optional: true
  belongs_to :done_by, class_name: 'User', optional: true

  validates :issue_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(issue)
    where(issue_id: issue.id).maximum(:position).to_i + 1
  end

  def self.normalize_positions_for(issue)
    where(issue_id: issue.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 done_metadata_available?
    has_attribute?(:done_by_id) && has_attribute?(:done_at)
  end

  def done_by_user
    return nil unless has_attribute?(:done_by_id)

    done_by
  end

  def done_at_time
    return nil unless has_attribute?(:done_at)

    self[:done_at]
  end

  def mark_done_by(user)
    self.is_done = true
    self.done_by = user if has_attribute?(:done_by_id)
    self.done_at = Time.current if has_attribute?(:done_at)
  end

  def reopen
    self.is_done = false
    self.done_by = nil if has_attribute?(:done_by_id)
    self.done_at = nil if has_attribute?(:done_at)
  end
end
