# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::BackgroundMigration::SetCorrectVulnerabilityState,
  schema: 20241112161754,
  feature_category: :vulnerability_management do
  before(:all) do
    # This migration will not work if a sec database is configured. It should be finalized and removed prior to
    # sec db rollout.
    # Consult https://gitlab.com/gitlab-org/gitlab/-/merge_requests/171707 for more info.
    skip_if_multiple_databases_are_setup(:sec)
  end

  let(:organization) { table(:organizations).create!(name: 'organization', path: 'organization') }
  let(:namespace) { table(:namespaces).create!(name: 'user', path: 'user', organization_id: organization.id) }
  let(:users) { table(:users) }
  let(:user) { create_user! }
  let(:project) do
    table(:projects).create!(
      namespace_id: namespace.id,
      project_namespace_id: namespace.id,
      organization_id: organization.id,
      packages_enabled: false
    )
  end

  let(:identifiers) { table(:vulnerability_identifiers) }
  let(:findings) { table(:vulnerability_occurrences) }
  let(:vulnerabilities) { table(:vulnerabilities) }

  let!(:scanner) { create_scanner!(project_id: project.id) }

  let!(:vulnerability_with_dismissed_at) do
    create_vulnerability!(
      project_id: project.id,
      author_id: user.id,
      dismissed_at: Time.current
    )
  end

  let!(:vulnerability_without_dismissed_at) do
    create_vulnerability!(
      project_id: project.id,
      author_id: user.id,
      dismissed_at: nil
    )
  end

  let(:detected_state) { 1 }
  let(:dismissed_state) { 2 }

  let(:migration_job) do
    described_class.new(
      start_id: vulnerability_with_dismissed_at.id,
      end_id: vulnerability_without_dismissed_at.id,
      batch_table: :vulnerabilities,
      batch_column: :id,
      sub_batch_size: 1,
      pause_ms: 0,
      connection: ActiveRecord::Base.connection
    )
  end

  describe '#filter_batch' do
    it 'filters out vulnerabilities where dismissed_at is null' do
      expect(migration_job.filter_batch(vulnerabilities)).to contain_exactly(vulnerability_with_dismissed_at)
    end
  end

  describe '#perform' do
    subject(:perform_migration) { migration_job.perform }

    it 'changes vulnerability state to `dismissed` when dismissed_at is not nil' do
      expect { perform_migration }.to change { vulnerability_with_dismissed_at.reload.state }.to(dismissed_state)
    end

    it 'does not change the state when dismissed_at is nil' do
      expect { perform_migration }.not_to change { vulnerability_without_dismissed_at.reload.state }
    end
  end

  private

  def create_scanner!(project_id:)
    table(:vulnerability_scanners).create!(
      project_id: project_id,
      external_id: "External ID",
      name: "Test Scanner"
    )
  end

  def create_vulnerability!(
    project_id:, author_id:, title: 'test', severity: 7, confidence: 7, report_type: 0, state: 1, dismissed_at: nil
  )
    identifier = identifiers.create!(
      project_id: project_id,
      external_type: 'uuid-v5',
      external_id: 'uuid-v5',
      fingerprint: OpenSSL::Digest.hexdigest('SHA256', SecureRandom.uuid),
      name: "Identifier for UUIDv5 #{project_id}"
    )

    finding = findings.create!(
      project_id: project_id, scanner_id: scanner.id,
      primary_identifier_id: identifier.id, name: 'test', severity: 4, confidence: 4, report_type: 0,
      uuid: SecureRandom.uuid, project_fingerprint: '123qweasdzxc',
      location_fingerprint: 'test', metadata_version: 'test',
      raw_metadata: "")

    vulnerabilities.create!(
      project_id: project_id,
      author_id: author_id,
      title: title,
      severity: severity,
      confidence: confidence,
      report_type: report_type,
      state: state,
      dismissed_at: dismissed_at,
      finding_id: finding.id
    )
  end

  def create_user!(name: "Example User", email: "user@example.com", user_type: nil)
    users.create!(
      name: name,
      email: email,
      username: name,
      projects_limit: 10
    )
  end
end
