# frozen_string_literal: true

module Gitlab
  module QA
    module Component
      class LicenseOps < Base
        LicenseError = Class.new(StandardError)
        require 'shellwords'

        def add_license(gitlab)
          license_key = fetch_license_key
          command = build_license_command(license_key)
          apply_license(gitlab, command, license_key)
        end

        private

        def fetch_license_key
          license_key = ENV.fetch('EE_LICENSE', '')
          raise LicenseError, "EE_LICENSE environment variable is not set or is empty" if license_key.empty?

          Shellwords.shellwords(license_key).join
        end

        def build_license_command(license_key)
          script = <<~RUBY
            key = ENV['EE_LICENSE']
            license = License.new(data: key)
            if license.save
              puts "License applied successfully"
            else
              STDERR.puts "Failed to apply license"
            end
          RUBY
          "EE_LICENSE='#{license_key}' gitlab-rails runner $'#{script.gsub("'", "\\\\'").gsub("\n", '\\n')}'"
        end

        def apply_license(gitlab, command, license_key)
          result = gitlab.docker.exec(gitlab.name, command, mask_secrets: license_key)
          verify_license_application(result)
        end

        def verify_license_application(result)
          return if result.include?("License applied successfully")

          raise LicenseError, "Failed to apply license."
        end
      end
    end
  end
end
