defmodule Towerops.Snmp.MacAddress do
  @moduledoc """
  SNMP MAC address schema for bridge forwarding database entries.

  Stores MAC address table entries discovered via BRIDGE-MIB
  dot1dTpFdbTable (1.3.6.1.2.1.17.4.3) and Q-BRIDGE-MIB
  dot1qTpFdbTable (1.3.6.1.2.1.17.7.1.2.2).
  """
  use Ecto.Schema

  import Ecto.Changeset

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "snmp_mac_addresses" do
    field :mac_address, :string
    field :vlan_id, :integer
    field :port_index, :integer
    field :entry_status, :string
    field :last_seen_at, :utc_datetime

    belongs_to :device, Towerops.Devices.Device
    belongs_to :interface, Towerops.Snmp.Interface

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(mac_address, attrs) do
    mac_address
    |> cast(attrs, [
      :device_id,
      :interface_id,
      :mac_address,
      :vlan_id,
      :port_index,
      :entry_status,
      :last_seen_at
    ])
    |> validate_required([
      :device_id,
      :mac_address,
      :last_seen_at
    ])
    |> foreign_key_constraint(:device_id)
    |> foreign_key_constraint(:interface_id)
    |> unique_constraint([:device_id, :mac_address, :vlan_id])
  end
end
