#!/usr/bin/env ruby

require "aws-sdk"

# Adding ability to our history client to flush data from DynamoDB
module AwsFlusher
  class DynamoDB
    TABLE_NAME = "history-staging" # Hardcoded. We do not want to accidentally delete production data. Modify manually.
    LIMIT = 25 # Numbers of records to fetch and delete in a batch
    AWS_REGION = "us-west-2"

    class << self
      # AWS client to perform scan & batch writes (for deletes)
      def aws_client
        @aws_client ||= Aws::DynamoDB::Client.new(region: AWS_REGION)
      end

      # Builds scan options to get items from DynamoDB
      def scan_options
        {
          table_name: TABLE_NAME,
          limit: LIMIT,
          attributes_to_get: ["uuid"],
        }
      end

      # Returns an array of items as a hash
      def scan_items
        aws_client.scan(scan_options).items
      end

      # Builds options for delete request referenced by uuids to be used in batch write item options
      def delete_request_options(uuids)
        uuids.map do |uuid|
          {
            delete_request: {
              key: {
                uuid: uuid
              }
            }
          }
        end
      end

      # Builds batch write item options but for deleting items references by uuids
      def batch_write_item_options(uuids)
        {
          request_items: {
            TABLE_NAME => delete_request_options(uuids)
          },
          return_consumed_capacity: "INDEXES",
          return_item_collection_metrics: "SIZE",
        }
      end

      # Performs the bulk delete operation using batch write item API
      def delete_items(uuids)
        print "Deleting #{uuids.length} record(s)... "

        options = batch_write_item_options(uuids)
        response = aws_client.batch_write_item options

        puts "Deleted #{response.consumed_capacity[0].table.capacity_units.to_i}"
      end

      # Loop through the items using scan & bulk delete until the table is empty
      def flush!
        loop do
          uuids = scan_items.map do |item|
            item["uuid"]
          end

          break if uuids.length.zero?

          delete_items(uuids)
        end
      end
    end
  end
end

AwsFlusher::DynamoDB.flush!
