defmodule Towerops.Topology.DeviceLinkEvidence do
  @moduledoc """
  Schema for evidence supporting a device link.

  Each piece of evidence records a specific observation (LLDP neighbor,
  CDP neighbor, MAC on interface, ARP entry, etc.) that contributed to
  the existence or confidence of a device link.
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Towerops.Topology.DeviceLink

  @valid_evidence_types ~w(lldp_neighbor cdp_neighbor mac_on_interface arp_entry wireless_registration subnet_match)

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "device_link_evidence" do
    field :evidence_type, :string
    field :evidence_data, :map, default: %{}
    field :observed_at, :utc_datetime

    belongs_to :device_link, DeviceLink

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(evidence, attrs) do
    evidence
    |> cast(attrs, [:device_link_id, :evidence_type, :evidence_data, :observed_at])
    |> validate_required([:device_link_id, :evidence_type, :observed_at])
    |> validate_inclusion(:evidence_type, @valid_evidence_types)
    |> foreign_key_constraint(:device_link_id)
  end
end
