# frozen_string_literal: true

require "spec_helper"

require_migration!

RSpec.describe DeleteMigrateSharedVulnerabilityScanners, :migration, feature_category: :vulnerability_management do
  let(:batched_background_migrations) { table(:batched_background_migrations) }
  let(:batched_background_migration_jobs) { table(:batched_background_migration_jobs) }

  let(:migration) do
    batched_background_migrations.create!(
      created_at: Time.zone.now,
      updated_at: Time.zone.now,
      min_value: 1,
      max_value: 1,
      batch_size: described_class::BATCH_SIZE,
      sub_batch_size: 100,
      interval: 300,
      status: 3,
      job_class_name: described_class::MIGRATION,
      batch_class_name: "PrimaryKeyBatchingStrategy",
      table_name: described_class::TABLE_NAME,
      column_name: described_class::BATCH_COLUMN,
      job_arguments: [],
      pause_ms: 100,
      max_batch_size: 1000,
      gitlab_schema: "gitlab_main"
    )
  end

  let(:jobs) do
    Array.new(10) do
      batched_background_migration_jobs.create!(
        batched_background_migration_id: migration.id,
        created_at: Time.zone.now,
        updated_at: Time.zone.now,
        min_value: 1,
        max_value: 1,
        batch_size: 1,
        sub_batch_size: 1,
        status: 0,
        attempts: 0,
        metrics: {},
        pause_ms: 100
      )
    end
  end

  describe "#up" do
    it "deletes jobs" do
      expect { migrate! }.to change(batched_background_migration_jobs, :count).from(jobs.count).to(0)
    end

    it "deletes the migration" do
      expect { migrate! }.to change { batched_background_migrations.find_by(id: migration.id) }.from(migration).to(nil)
    end

    context "when background migration does not exist" do
      before do
        migration.destroy!
      end

      it "does not delete jobs" do
        expect { migrate! }.not_to change(batched_background_migration_jobs, :count)
      end

      it "does not delete the migration" do
        expect { migrate! }.not_to change { batched_background_migrations.find_by(id: migration.id) }
      end
    end
  end
end