# frozen_string_literal: true

class CreateNetworkRanges < ActiveRecord::Migration[8.1]
  def change
    create_table :network_ranges, force: :cascade do |t|
      # Postgres inet type handles both IPv4 and IPv6 networks
      t.inet :network, null: false, index: { unique: true, name: 'index_network_ranges_on_network_unique' }


      # Track the source of this network range
      t.string :source, default: 'api_imported', null: false, index: true
      t.text :creation_reason

      # Network intelligence metadata
      t.integer :asn, index: true
      t.string :asn_org, index: true
      t.string :company, index: true
      t.string :country, index: true

      # Network classification flags
      t.boolean :is_datacenter, default: false, index: true
      t.boolean :is_proxy, default: false
      t.boolean :is_vpn, default: false
      t.index [:is_datacenter, :is_proxy, :is_vpn], name: 'idx_network_flags'

      # JSON fields for additional data
      t.text :abuser_scores
      t.text :additional_data

      # API enrichment tracking
      t.datetime :last_api_fetch

      # Track creation (optional - some ranges are auto-imported)
      t.references :user, foreign_key: true

      t.timestamps

      # Postgres network indexes for performance
      # GiST index for network containment operations (>>=, <<=, &&)
      t.index :network, using: :gist, opclass: :inet_ops
    end
  end
end