defmodule Towerops.Snmp.MemoryPool do
  @moduledoc """
  SNMP memory pool schema for tracking RAM, swap, and other memory types.

  Memory pools are discovered via:
  - HOST-RESOURCES-MIB hrStorageTable (RAM, virtual memory)
  - UCD-SNMP-MIB memory group (Linux memory stats)

  Tracks total and used memory for capacity monitoring.
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Ecto.Association.NotLoaded
  alias Towerops.Snmp.Device

  @valid_pool_types ~w(ram swap cache buffer other)

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "snmp_memory_pools" do
    field :pool_index, :string
    field :pool_name, :string
    field :pool_type, :string
    field :total_bytes, :integer
    field :used_bytes, :integer
    field :last_checked_at, :utc_datetime
    field :metadata, :map, default: %{}

    belongs_to :snmp_device, Device

    timestamps(type: :utc_datetime)
  end

  @type t :: %__MODULE__{
          id: Ecto.UUID.t(),
          pool_index: String.t(),
          pool_name: String.t() | nil,
          pool_type: String.t(),
          total_bytes: integer() | nil,
          used_bytes: integer() | nil,
          last_checked_at: DateTime.t() | nil,
          metadata: map(),
          snmp_device_id: Ecto.UUID.t(),
          snmp_device: NotLoaded.t() | Device.t(),
          inserted_at: DateTime.t(),
          updated_at: DateTime.t()
        }

  @doc false
  def changeset(memory_pool, attrs) do
    memory_pool
    |> cast(attrs, [
      :snmp_device_id,
      :pool_index,
      :pool_name,
      :pool_type,
      :total_bytes,
      :used_bytes,
      :last_checked_at,
      :metadata
    ])
    |> validate_required([:snmp_device_id, :pool_index, :pool_type])
    |> validate_inclusion(:pool_type, @valid_pool_types)
    |> unique_constraint([:snmp_device_id, :pool_index])
    |> foreign_key_constraint(:snmp_device_id)
  end
end
