# frozen_string_literal: true

class UxToolkitTrackerTicketTemplate < ApplicationRecord
  belongs_to :tracker
  belongs_to :project, optional: true
  belongs_to :ticket_template,
             class_name: 'UxToolkitTicketTemplate',
             optional: true

  validates :tracker_id,
            presence: true,
            uniqueness: {scope: :project_id}
  validates :ticket_template_id, presence: true

  scope :global, -> { where(project_id: nil) }
  scope :enabled, -> { where(enabled: true) }
  scope :available, -> { enabled.joins(:ticket_template).merge(UxToolkitTicketTemplate.enabled) }

  def self.table_available?
    table_exists?
  rescue ActiveRecord::NoDatabaseError, ActiveRecord::StatementInvalid
    false
  end

  def self.save_global_defaults_from_params(default_params)
    return unless default_params

    defaults = default_params || {}
    enabled_template_ids = UxToolkitTicketTemplate.enabled.pluck(:id).map(&:to_s)

    transaction do
      Tracker.sorted.each do |tracker|
        attributes = defaults[tracker.id.to_s] || {}
        template_id = attributes['ticket_template_id'].to_s
        enabled = attributes['enabled'].to_s == '1'
        default = global.find_or_initialize_by(tracker: tracker)

        if template_id.blank?
          default.destroy! if default.persisted?
          next
        end

        unless enabled_template_ids.include?(template_id)
          default.errors.add(:ticket_template_id, :invalid)
          raise ActiveRecord::RecordInvalid, default
        end

        default.update!(ticket_template_id: template_id, enabled: enabled)
      end
    end
  end
end
