1# frozen_string_literal: true
2
3module API
4  module Entities
5    class Environment < Entities::EnvironmentBasic
6      include RequestAwareEntity
7      include Gitlab::Utils::StrongMemoize
8
9      expose :project, using: Entities::BasicProjectDetails
10      expose :last_deployment, using: Entities::Deployment, if: { last_deployment: true }
11      expose :state
12
13      expose :enable_advanced_logs_querying, if: -> (*) { can_read_pod_logs? } do |environment|
14        environment.elastic_stack_available?
15      end
16
17      expose :logs_api_path, if: -> (*) { can_read_pod_logs? } do |environment|
18        if environment.elastic_stack_available?
19          elasticsearch_project_logs_path(environment.project, environment_name: environment.name, format: :json)
20        else
21          k8s_project_logs_path(environment.project, environment_name: environment.name, format: :json)
22        end
23      end
24
25      expose :gitlab_managed_apps_logs_path, if: -> (*) { can_read_pod_logs? && cluster } do |environment|
26        ::Clusters::ClusterPresenter.new(cluster, current_user: current_user).gitlab_managed_apps_logs_path # rubocop: disable CodeReuse/Presenter
27      end
28
29      private
30
31      alias_method :environment, :object
32
33      def can_read_pod_logs?
34        strong_memoize(:can_read_pod_logs) do
35          current_user&.can?(:read_pod_logs, environment.project)
36        end
37      end
38
39      def cluster
40        strong_memoize(:cluster) do
41          environment&.last_deployment&.cluster
42        end
43      end
44
45      def current_user
46        options[:current_user]
47      end
48    end
49  end
50end
51