# frozen_string_literal: true

require 'spec_helper'

RSpec.describe Gitlab::BackgroundMigration::BackfillVulnerabilityReadsClusterAgent, :migration, schema: 20240116205430 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(:migration) do
    described_class.new(
      start_id: 1, end_id: 10,
      batch_table: table_name, batch_column: batch_column,
      sub_batch_size: sub_batch_size, pause_ms: pause_ms,
      connection: ApplicationRecord.connection
    )
  end

  let(:users_table) { table(:users) }
  let(:identifiers_table) { table(:vulnerability_identifiers) }
  let(:vulnerability_findings) { table(:vulnerability_occurrences) }
  let(:vulnerability_reads_table) { table(:vulnerability_reads) }
  let(:vulnerability_scanners_table) { table(:vulnerability_scanners) }
  let(:vulnerabilities_table) { table(:vulnerabilities) }
  let(:organizations_table) { table(:organizations) }
  let(:namespaces_table) { table(:namespaces) }
  let(:projects_table) { table(:projects) }
  let(:cluster_agents_table) { table(:cluster_agents) }

  let(:table_name) { 'vulnerability_reads' }
  let(:batch_column) { :id }
  let(:sub_batch_size) { 1_000 }
  let(:pause_ms) { 0 }

  before do
    users_table.create!(id: 1, name: 'John Doe', email: 'test@example.com', projects_limit: 5)

    organizations_table.create!(id: 1, name: 'Organization', path: 'organization')

    namespaces_table.create!(id: 1, name: 'Namespace 1', path: 'namespace-1', organization_id: 1)
    namespaces_table.create!(id: 2, name: 'Namespace 2', path: 'namespace-2', organization_id: 1)

    projects_table.create!(id: 1, namespace_id: 1, name: 'p1', path: 'p-1', project_namespace_id: 1, organization_id: 1)
    projects_table.create!(id: 2, namespace_id: 2, name: 'p2', path: 'p-2', project_namespace_id: 2, organization_id: 1)

    cluster_agents_table.create!(id: 1, name: 'Agent 1', project_id: 1)
    cluster_agents_table.create!(id: 2, name: 'Agent 2', project_id: 2)

    vulnerability_scanners_table.create!(id: 1, project_id: 1, external_id: 'starboard', name: 'Starboard')
    vulnerability_scanners_table.create!(id: 2, project_id: 2, external_id: 'starboard', name: 'Starboard')

    identifier1 = add_identifier!(project_id: 1)
    identifier2 = add_identifier!(project_id: 2)

    add_vulnerability_read!(1, project_id: 1, identifier: identifier1, cluster_agent_id: 1,
      report_type: 7)
    add_vulnerability_read!(3, project_id: 1, identifier: identifier1, cluster_agent_id: 2,
      report_type: 7)
    add_vulnerability_read!(5, project_id: 2, identifier: identifier2, cluster_agent_id: 2,
      report_type: 5)
    add_vulnerability_read!(7, project_id: 2, identifier: identifier2, cluster_agent_id: 3,
      report_type: 7)
    add_vulnerability_read!(9, project_id: 2, identifier: identifier2, cluster_agent_id: 2,
      report_type: 7)
    add_vulnerability_read!(10, project_id: 1, identifier: identifier1, cluster_agent_id: 1,
      report_type: 7)
    add_vulnerability_read!(11, project_id: 1, identifier: identifier1, cluster_agent_id: 1,
      report_type: 7)
  end

  describe '#filter_batch' do
    it 'pick only vulnerability reads where report_type = 7' do
      expect(migration.filter_batch(vulnerability_reads_table).pluck(:id)).to contain_exactly(1, 3, 7, 9, 10, 11)
    end
  end

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

    it 'backfills `casted_cluster_agent_id` for the selected records', :aggregate_failures do
      queries = ActiveRecord::QueryRecorder.new do
        perform_migration
      end

      expect(queries.count).to eq(3)
      expect(vulnerability_reads_table.where.not(casted_cluster_agent_id: nil).count).to eq 3
      expect(vulnerability_reads_table.where.not(casted_cluster_agent_id: nil).pluck(:id)).to match_array([1, 9, 10])
    end

    it 'tracks timings of queries' do
      expect(migration.batch_metrics.timings).to be_empty

      expect { perform_migration }.to change { migration.batch_metrics.timings }
    end
  end

  private

  def add_identifier!(project_id:)
    identifiers_table.create!(
      project_id: project_id,
      fingerprint: SecureRandom.hex(20),
      external_id: "cwe-2021-1234",
      external_type: "cwe",
      name: "CWE-73"
    )
  end

  def add_vulnerability_read!(id, identifier:, project_id:, cluster_agent_id:, report_type:)
    finding = vulnerability_findings.create!(
      project_id: project_id,
      scanner_id: project_id,
      severity: 5, # medium
      report_type: 0, # sast
      primary_identifier_id: identifier.id,
      project_fingerprint: SecureRandom.hex(20),
      location_fingerprint: SecureRandom.hex(20),
      uuid: SecureRandom.uuid,
      name: identifier.name,
      raw_metadata: "{}",
      metadata_version: "test:1.0"
    )

    vulnerabilities_table.create!(
      id: id,
      project_id: project_id,
      author_id: 1,
      finding_id: finding.id,
      title: "Vulnerability #{id}",
      severity: finding.severity,
      confidence: 5,
      report_type: report_type
    )

    vulnerability_reads_table.create!(
      id: id,
      uuid: SecureRandom.uuid,
      severity: 5,
      state: 1,
      vulnerability_id: id,
      scanner_id: project_id,
      cluster_agent_id: cluster_agent_id.to_s,
      project_id: project_id,
      report_type: report_type
    )
  end
end
