# frozen_string_literal: true

require_relative 'utils/chef'
require_relative 'utils/secrets'
require_relative 'utils/ssm'

require 'datadog/lambda'
require 'sentry-ruby'

Datadog::Lambda.configure_apm do |c|
  # Enable the instrumentation
end

Sentry.init do |config|
  config.dsn = Config::SENTRY_DSN
  config.traces_sample_rate = 1.0
end

module LambdaFunction
  # Handles requests to create SSM activations and store the activation details in an encrypted Chef data bag.
  class Handler
    include Logging

    def self.data_bag_data(activation:)
      {
        'id' => Config::CHEF_DATA_BAG_ITEM_NAME,
        'activation_id' => activation['activation_id'],
        'activation_code' => activation['activation_code']
      }
    end

    def self.store_activation(event:, activation:)
      Utils::Chef.configure(
        chef_server_url: event['chef_server_url'],
        chef_client_key: Utils::Secrets.get_secret(event['chef_client_key_secret_id']),
        cert_s3_bucket: event['chef_server_cert_s3_bucket'],
        cert_s3_key: event['chef_server_cert_s3_key']
      )
      Utils::Chef.create_encrypted_data_bag(
        data: data_bag_data(activation: activation),
        secret: Utils::Secrets.get_secret(event['chef_encrypted_data_bag_secret_id'])
      )
    end

    def self.process(event:, context:)
      Datadog::Lambda.wrap(event, context) do
        logger.info("Received event: #{event}")
        activation = Utils::SSM.create_activation(description: "Created automatically by #{context.function_name}")
        store_activation(event: event, activation: activation)
      rescue StandardError => e
        Sentry.capture_exception(e)
        raise e
      end
    end
  end
end
