# frozen_string_literal: true

require 'spec_helper'
require_migration!

RSpec.describe UpdateVulnerabilityOccurrencesLocation, :migration do
  let(:migration_name) { 'UpdateVulnerabilityOccurrencesLocation' }

  let_it_be(:namespaces) { table(:namespaces) }
  let_it_be(:group) { namespaces.create!(name: 'foo', path: 'foo', type: Group.sti_name) }
  let_it_be(:projects) { table(:projects) }
  let_it_be(:findings) { table(:vulnerability_occurrences) }
  let_it_be(:scanners) { table(:vulnerability_scanners) }
  let_it_be(:identifiers) { table(:vulnerability_identifiers) }

  let_it_be(:project) { projects.create!(id: 123, namespace_id: group.id, name: 'gitlab', path: 'gitlab') }

  let_it_be(:scanner) do
    scanners.create!(id: 6, project_id: project.id, external_id: 'trivy', name: 'Security Scanner')
  end

  let_it_be(:identifier) do
    identifiers.create!(id: 123,
                        project_id: 123,
                        fingerprint: 'd432c2ad2953e8bd587a3a43b3ce309b5b0154c123',
                        external_type: 'SECURITY_ID',
                        external_id: 'SECURITY_0',
                        name: 'SECURITY_IDENTIFIER 0')
  end

  let_it_be(:location) do
    { "file" => "maven/src/main/java/com/gitlab/security_products/tests/App.java", "start_line" => 29, "end_line" => 29, "class" => "com.gitlab.security_products.tests.App", "method" => "insecureCypher" }
  end

  let_it_be(:vul1) { findings.create!(finding_params) }
  let_it_be(:vul2) { findings.create!(finding_params) }
  let_it_be(:vul3) { findings.create!(finding_params(location)) }

  it 'correctly schedules background migrations' do
    Sidekiq::Testing.fake! do
      freeze_time do
        migrate!

        expect(BackgroundMigrationWorker.jobs.size).to eq(1)
        expect(migration_name).to be_scheduled_migration_with_multiple_args(vul1.id, vul2.id)
      end
    end
  end

  private

  def finding_params(location = nil)
    uuid = SecureRandom.uuid

    {
      severity: 0,
      confidence: 5,
      report_type: 2,
      project_id: 123,
      scanner_id: 6,
      primary_identifier_id: 123,
      location: location,
      project_fingerprint: SecureRandom.hex(20),
      location_fingerprint: Digest::SHA1.hexdigest(SecureRandom.hex(10)),
      uuid: uuid,
      name: "Vulnerability Finding #{uuid}",
      metadata_version: '1.3',
      raw_metadata: { location: location }.to_json
    }
  end
end
