# frozen_string_literal: true

module WPScan
  # Filter for excluding specific vulnerabilities by UUID
  class VulnerabilityFilter
    attr_reader :excluded_uuids, :excluded_count

    # @param [ Array<String>, String, nil ] uuids UUID identifiers to exclude
    def initialize(uuids = nil)
      @excluded_uuids = normalize_uuids(uuids)
      @excluded_count = 0
    end

    # Filter vulnerabilities, removing those with excluded UUIDs
    #
    # @param [ Array<Vulnerability> ] vulnerabilities
    # @return [ Array<Vulnerability> ] Filtered vulnerabilities
    def filter(vulnerabilities)
      return vulnerabilities if excluded_uuids.empty?

      vulnerabilities.reject do |vuln|
        should_exclude?(vuln).tap do |excluded|
          @excluded_count += 1 if excluded
        end
      end
    end

    # Check if a vulnerability should be excluded
    #
    # @param [ Vulnerability ] vulnerability
    # @return [ Boolean ]
    def should_exclude?(vulnerability)
      return false if excluded_uuids.empty?
      return false unless vulnerability.uuid

      # Check UUID match (case-insensitive)
      excluded_uuids.include?(vulnerability.uuid.downcase)
    end

    # Reset the excluded count
    def reset_count!
      @excluded_count = 0
    end

    # Check if any UUIDs are being excluded
    #
    # @return [ Boolean ]
    def excluding?
      !excluded_uuids.empty?
    end

    private

    # Normalize UUIDs
    #
    # @param [ Array<String>, String, nil ] uuids
    # @return [ Array<String> ] Normalized UUIDs
    def normalize_uuids(uuids)
      return [] if uuids.nil?

      # Convert string to array if needed
      uuids = uuids.is_a?(String) ? uuids.split(',') : Array(uuids)

      # Normalize each UUID (trim whitespace, lowercase, remove duplicates)
      uuids.map { |u| u.to_s.strip.downcase }.reject(&:empty?).uniq
    end
  end
end
