# frozen_string_literal: true

class UxToolkitTrackerNotice < ApplicationRecord
  belongs_to :tracker

  validates :tracker_id, presence: true, uniqueness: true

  before_validation :normalize_blank_notice

  def self.notice_text_for(tracker)
    return nil unless tracker

    find_by(tracker_id: tracker.id)&.new_issue_notice_text
  end

  def self.save_all_from_params(notice_params)
    return unless notice_params

    notices = notice_params || {}

    Tracker.sorted.each do |tracker|
      text = notices.dig(tracker.id.to_s, 'new_issue_notice_text')
      notice = find_or_initialize_by(tracker: tracker)

      if text.blank?
        notice.destroy if notice.persisted?
        next
      end

      notice.new_issue_notice_text = text
      notice.save!
    end
  end

  private

  def normalize_blank_notice
    self.new_issue_notice_text = nil if new_issue_notice_text.blank?
  end
end
