defmodule Towerops.Snmp.InterfaceStat do
  @moduledoc """
  Time-series interface statistics schema.

  Stores interface counter values (octets, errors, discards) collected
  during SNMP polling. Stored in TimescaleDB hypertable.
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Towerops.Snmp.Interface

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "snmp_interface_stats" do
    field :if_in_octets, :integer
    field :if_out_octets, :integer
    field :if_in_errors, :integer
    field :if_out_errors, :integer
    field :if_in_discards, :integer
    field :if_out_discards, :integer
    field :checked_at, :utc_datetime

    belongs_to :interface, Interface

    timestamps(type: :utc_datetime, updated_at: false)
  end

  @type t :: %__MODULE__{
          id: Ecto.UUID.t(),
          if_in_octets: integer() | nil,
          if_out_octets: integer() | nil,
          if_in_errors: integer() | nil,
          if_out_errors: integer() | nil,
          if_in_discards: integer() | nil,
          if_out_discards: integer() | nil,
          checked_at: DateTime.t(),
          interface_id: Ecto.UUID.t(),
          interface: Ecto.Association.NotLoaded.t() | Interface.t(),
          inserted_at: DateTime.t()
        }

  @doc false
  def changeset(stat, attrs) do
    stat
    |> cast(attrs, [
      :interface_id,
      :if_in_octets,
      :if_out_octets,
      :if_in_errors,
      :if_out_errors,
      :if_in_discards,
      :if_out_discards,
      :checked_at
    ])
    |> validate_required([:interface_id, :checked_at])
    |> foreign_key_constraint(:interface_id)
  end
end
