require 'bunny'

require 'debci'

module Debci
  module AMQP
    # Some queues are used for multiple backends
    QUEUE_ALIASES = {
      'incus-lxc' => 'lxc',
      'lxd-lxc' => 'lxc',
    }.freeze

    def self.get_queue(arch, backend = Debci.config.backend)
      opts = {
        durable: true,
        arguments: {
          'x-max-priority': 10,
        }
      }
      q = queue_name(arch, backend)
      self.amqp_channel.queue(q, opts)
    end

    def self.queue_exists?(arch, backend)
      conn.queue_exists?(queue_name(arch, backend))
    end

    def self.queue_name(arch, backend)
      queue_type = QUEUE_ALIASES[backend] || backend
      "debci-tests-#{arch}-#{queue_type}"
    end

    def self.results_queue
      q = Debci.config.amqp_results_queue
      self.amqp_channel.queue(q, durable: true)
    end

    def self.conn
      @conn ||= Bunny.new(Debci.config.amqp_server, amqp_options).tap do |c|
        c.start
      end
    end

    def self.amqp_channel
      @channel ||= conn.create_channel
    end

    def self.amqp_options
      {
        tls:                  Debci.config.amqp_ssl,
        tls_cert:             Debci.config.amqp_cert,
        tls_ca_certificates:  Debci.config.amqp_cacert,
        tls_key:              Debci.config.amqp_key,
        verify_peer:          true,
      }
    end
  end
end
