defmodule Towerops.GeoIP.Block do
  @moduledoc """
  Schema for GeoIP IP block data (CIDR ranges mapped to locations).
  Maps IP address ranges to geoname_id from MaxMind GeoLite2-City database.
  """
  use Ecto.Schema

  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  schema "geoip_blocks" do
    field :network, :string
    field :start_ip_int, :integer
    field :end_ip_int, :integer
    field :registered_country_geoname_id, :integer

    belongs_to :location, Towerops.GeoIP.Location,
      foreign_key: :geoname_id,
      references: :geoname_id,
      type: :integer

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(block, attrs) do
    block
    |> cast(attrs, [
      :network,
      :start_ip_int,
      :end_ip_int,
      :geoname_id,
      :registered_country_geoname_id
    ])
    |> validate_required([:network, :start_ip_int, :end_ip_int])
  end
end
