# frozen_string_literal: true

class UxToolkitTrackerChecklistTemplate < ApplicationRecord
  belongs_to :tracker, optional: true
  belongs_to :checklist_template,
             class_name: 'UxToolkitChecklistTemplate',
             optional: true

  validates :tracker_id, presence: true, uniqueness: true
  validates :checklist_template_id, presence: true
  validate :checklist_template_is_available

  scope :for_tracker, ->(tracker_id) { where(tracker_id: tracker_id) }

  private

  def checklist_template_is_available
    return if checklist_template&.active? && checklist_template.items.exists?

    errors.add(:checklist_template_id, :invalid)
  end
end
