# Copyright 2025 Google LLC
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.

require "io/console"
require_relative "../config/environment"
require_relative "models/singer"
require_relative "models/album"

class Application
  def self.run
    first_names = %w[Pete Alice John Ethel Trudy Naomi Wendy Ruben Thomas Elly]
    last_names = %w[Wendelson Allison Peterson Johnson Henderson Ericsson Aronson Tennet Courtou]

    # Insert 5 new singers using Batch DML.
    ActiveRecord::Base.transaction do
      # The Base.dml_batch function starts a DML batch. All DML statements that are
      # generated by ActiveRecord inside the block that is given will be added to
      # the current batch. The batch is executed at the end of the block. The data
      # that has been written is readable after the block ends.
      ActiveRecord::Base.dml_batch do
        5.times do
          Singer.create first_name: first_names.sample, last_name: last_names.sample
        end
      end
      # Data that has been inserted/update using Batch DML can be read in the same
      # transaction as the one that added/updated the data. This is different from
      # mutations, as mutations do not support read-your-writes.
      singers = Singer.all
      puts "Inserted #{singers.count} singers in one batch"
    end

    # Batch DML can also be used to update existing data.
    ActiveRecord::Base.transaction do
      # Start a DML batch.
      singers = nil
      ActiveRecord::Base.dml_batch do
        # Queries can be executed inside a DML batch.
        # These are executed directly and do not affect the DML batch.
        singers = Singer.all
        singers.each do |singer|
          singer.picture = Base64.encode64 SecureRandom.alphanumeric(SecureRandom.random_number(10..200))
          singer.save
        end
      end
      puts "Updated #{singers.count} singers in one batch"
    end
  end
end


Application.run
