1# frozen_string_literal: true
2
3module Peek
4  module Views
5    class BulletDetailed < DetailedView
6      WARNING_MESSAGE = "Unoptimized queries detected"
7
8      def key
9        'bullet'
10      end
11
12      def results
13        return {} unless ::Bullet.enable?
14        return {} unless calls > 0
15
16        {
17          calls: calls,
18          details: details,
19          warnings: [WARNING_MESSAGE]
20        }
21      end
22
23      private
24
25      def details
26        notifications.map do |notification|
27          # there is no public method which returns pure backtace:
28          # https://github.com/flyerhzm/bullet/blob/9cda9c224a46786ecfa894480c4dd4d304db2adb/lib/bullet/notification/n_plus_one_query.rb
29          backtrace = notification.body_with_caller
30
31          {
32            notification: "#{notification.title}: #{notification.body}",
33            backtrace: backtrace
34          }
35        end
36      end
37
38      def calls
39        notifications.size
40      end
41
42      def notifications
43        ::Bullet.notification_collector&.collection || []
44      end
45    end
46  end
47end
48