# frozen_string_literal: true

class UxToolkitTicketTemplate < ApplicationRecord
  SUBJECT_TEMPLATE_MODES = %w[prefix default].freeze

  has_many :tracker_ticket_templates,
           class_name: 'UxToolkitTrackerTicketTemplate',
           foreign_key: 'ticket_template_id',
           dependent: :destroy

  validates :name,
            presence: true,
            length: {maximum: 255},
            uniqueness: {case_sensitive: false}
  validates :subject_template, length: {maximum: 255}, allow_blank: true
  validates :subject_template_mode, inclusion: {in: SUBJECT_TEMPLATE_MODES}
  validates :position,
            numericality: {only_integer: true, greater_than_or_equal_to: 0}

  scope :enabled, -> { where(enabled: true) }
  scope :ordered, -> { order(:position, Arel.sql('LOWER(name)'), :id) }

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