defmodule Towerops.DeviceProfiles.SensorDefinition do
  @moduledoc """
  Schema for sensor definitions.

  Defines OID mappings and configurations for discovering and polling
  device sensors (temperature, voltage, power, etc.).
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Towerops.DeviceProfiles.DeviceProfile
  alias Towerops.DeviceProfiles.SensorState
  alias Towerops.EctoTypes.JsonAny

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id

  schema "profile_sensor_definitions" do
    field :sensor_class, :string
    field :oid, JsonAny
    field :num_oid, JsonAny
    field :index, :string
    field :descr, :string
    field :divisor, :integer, default: 1
    field :multiplier, :integer, default: 1
    field :precision, :integer
    field :sensor_type, :string
    field :unit, :string
    field :low_limit, :float
    field :low_warn_limit, :float
    field :warn_limit, :float
    field :high_limit, :float
    field :skip_value_lt, :float
    field :skip_value_gt, :float
    field :user_func, :string
    field :entPhysicalIndex, JsonAny
    field :group, :string
    field :options, :map

    belongs_to :device_profile, DeviceProfile
    has_many :states, SensorState, foreign_key: :sensor_definition_id

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(definition, attrs) do
    definition
    |> cast(attrs, [
      :sensor_class,
      :oid,
      :num_oid,
      :index,
      :descr,
      :divisor,
      :multiplier,
      :precision,
      :sensor_type,
      :unit,
      :low_limit,
      :low_warn_limit,
      :warn_limit,
      :high_limit,
      :skip_value_lt,
      :skip_value_gt,
      :user_func,
      :entPhysicalIndex,
      :group,
      :options,
      :device_profile_id
    ])
    |> validate_required([:sensor_class, :device_profile_id])
    |> foreign_key_constraint(:device_profile_id)
  end
end
