Rake::TaskManager.record_task_metadata = true
namespace :audits do |auditor|

  ### These should remain the same for every run
  task_audit_created_at = Time.now.utc.round(3).iso8601(3)
  task_audit_expiry = 30.days
  task_audit_user_id = 20037 # 'kappa', as used in our feature tests

  desc "Generate audits with IP information"
  task session: :environment do

    require "history_client"
    require "pp"

    History::QueryAudit.audit_types_with_ip_information.each do |audit_type|
      changes = [
        History::ChangeSet.new(
          attribute: "audit_source",
          new_value: "audits.rake"
        )
      ]
      description = "IP address: 64.125.35.114"

      # rubocop:disable Lint/EmptyWhen
      case audit_type
      when History::AUDIT_LOGIN_EVENT
        change = History::ChangeSet.new(
          attribute: "authentication_source",
          new_value: "password"
        )
        changes.push(change)
      when History::AUDIT_SESSION_START_EVENT
        # nothing special for this audit type, but we know it exists
      when History::AUDIT_SESSION_INVALIDATE_EVENT
        # nothing special for this audit type, but we know it exists
      else
        warning = "Unknown audit type in `audit_types_with_ip_information`: #{audit_type}"
        puts warning
        Rails.logger.warn warning
      end
      # rubocop:enable Lint/EmptyWhen

      audit = History::Audit.new(
        action: audit_type,
        user_type: History::AUDIT_TWITCH_USER,
        user_id: task_audit_user_id,
        resource_type: History::AUDIT_TWITCH_USER,
        resource_id: task_audit_user_id,
        changes: changes,
        created_at: task_audit_created_at,
        expiry: task_audit_expiry,
        description: description
      )

      pre = "Generating audit: #{audit}"
      puts pre
      Rails.logger.info pre

      response = History::AddAudit.client.add(audit)
      if response.success?
        puts "Success"
        Rails.logger.info "Success"
      end

      next if response.success?

      puts "FAILED"
      pp response.inspect
      Rails.logger.fatal "FAILED"
      Rails.logger.fatal response.pretty_inspect
    end
  end

  ###

  desc "Generate audits for all available audit types"
  task :all do
    auditor.tasks.each do |task|
      Rake::Task[task].invoke
    end
  end
end

desc "List available Audit generators"
task :audits do
  Rake.application.options.show_tasks = :tasks
  Rake.application.options.show_task_pattern = /^audits:/
  Rake.application.display_tasks_and_comments
end
task audit: 'audits'
