module DataHelpers
  class AccountingStatementAttachments
    def initialize(opts = {})
      @opts = opts
    end

    def upload_successful?
      file = query_success_items.find { |i| i["original_file_name"] == @opts[:file_name] }
      return false unless file
      recently_recorded?(Time.parse(file["upload_date"]))
    end

    def upload_error?
      files = query_error_items.select do |i|
        i["file_name"].include?(@opts[:file_name])
      end
      return false if files.empty?
      file = files.sort_by { |x| x["event_time"] }.last
      recently_recorded?(Time.parse(file["event_time"]))
    end

    private

    def query_success_items
      params = {
        table_name: "qa_statement_attachments_success",
        key_condition_expression: "#label_type_id_period_id = :label_type_id_period_id",
        expression_attribute_names: {
          "#label_type_id_period_id" => "label_type_id_period_id"
        },
        expression_attribute_values: {
          ":label_type_id_period_id" => "L#{@opts[:label_id]}_#{@opts[:period_id]}"
        }
      }
      dynamodb_client.query(params).items
    end

    def query_error_items
      params = { table_name: "qa_statement_attachments_error" }
      dynamodb_client.scan(params).items
    end

    def recently_recorded?(upload_date, duration_to_check = 300)
      upload_date.between?(Time.now.utc - duration_to_check, Time.now.utc)
    end

    def dynamodb_client
      @dynamodb_client ||= Support::DynamoDbClient.new.client
    end
  end
end
