lib/wolf_core/infrastructure/lambda_function_operations.rb



module WolfCore
  module LambdaFunctionOperations
    include WolfCore::ExceptionOperations
    include WolfCore::StringUtils

    def invoke_lambda(function_name:, payload:, invocation_type: nil)
      WolfCore::LambdaFunctionDataSource.invoke(
        function_name: function_name, payload: payload, invocation_type: invocation_type
      )
    end

    def validate_lambda_response(response:, message:, error_data: nil)
      unless response.status_code == 200
        error_data = {
          message: message,
          response: parse_lambda_response(response)
        }.merge(error_data || {})
        raise_service_error(error_data)
      end
    end

    def parse_lambda_response(response)
      payload = JSON.parse(response.payload.string) rescue response.payload
      OpenStruct.new({
        status_code: response.status_code,
        payload: payload,
      })
    end

    def get_event_params(event)
      event_body = event['body']
      params = if event_body.present?
        deep_parse_json(event_body)
      else
        event
      end
      params&.with_indifferent_access
    end

    def result_to_response(result)
      if result.success?
        { statusCode: 200, body: result.data.to_h.to_json }
      else
        { statusCode: result.error.status || 422, body: result.error.to_h.to_json }
      end
    end
  end
end