# frozen_string_literal: true

module ReleaseTools
  module Promotion
    module Checks
      # OrchestratorStatus checks the status of orchestrator
      class OrchestratorStatus
        include ::ReleaseTools::Promotion::Check
        include ::SemanticLogger::Loggable

        HEADING = ':crystal_ball: GitLab Deployment Orchestrator Status'

        ORCHESTRATOR_KEY = 'group-delivery/deployment/orchestrator'

        def consul_client
          @consul_client ||= ReleaseTools::Consul::Client.new
        end

        def fine?
          return true unless ReleaseTools::Feature.enabled?(:check_orchestrator_status)

          orchestrator_enabled?
        end

        def to_slack_blocks
          [{ type: 'section', text: mrkdwn(status_message) }]
        end

        def to_issue_body
          status_message
        end

        def name
          'orchestrator status'
        end

        private

        def status_message
          "#{icon(self)} Orchestrator is #{fine? ? 'enabled' : 'disabled'}"
        end

        def orchestrator_enabled?
          return @orchestrator_enabled if defined?(@orchestrator_enabled)

          @orchestrator_enabled ||=
            begin
              status = JSON.parse(consul_client.get(ORCHESTRATOR_KEY))

              if status['status'] == 'enabled'
                logger.debug('Orchestrator is enabled', status: status)
                true
              else
                logger.debug('Orchestrator is disabled', status: status)
                false
              end
            rescue StandardError => ex
              logger.fatal('Failed checking Orchestrator status', ex)

              false
            end
        end
      end
    end
  end
end
