defmodule Towerops.Snmp.SensorReading do
  @moduledoc """
  Time-series sensor reading schema.

  Stores individual sensor readings (value, status, timestamp) collected
  during SNMP polling cycles. Stored in TimescaleDB hypertable.
  """
  use Ecto.Schema

  import Ecto.Changeset

  alias Towerops.Snmp.Sensor

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "snmp_sensor_readings" do
    field :value, :float
    field :status, :string
    field :state_descr, :string
    field :checked_at, :utc_datetime

    belongs_to :sensor, Sensor

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

  @type t :: %__MODULE__{
          id: Ecto.UUID.t(),
          value: float() | nil,
          status: String.t(),
          state_descr: String.t() | nil,
          checked_at: DateTime.t(),
          sensor_id: Ecto.UUID.t(),
          sensor: Ecto.Association.NotLoaded.t() | Sensor.t(),
          inserted_at: DateTime.t()
        }

  @doc false
  def changeset(reading, attrs) do
    reading
    |> cast(attrs, [:sensor_id, :value, :status, :state_descr, :checked_at])
    |> validate_required([:sensor_id, :status, :checked_at])
    |> validate_inclusion(:status, ["ok", "warning", "critical", "error"])
    |> foreign_key_constraint(:sensor_id)
  end
end
