defmodule Microwaveprop.Commercial.Sample do
  @moduledoc false
  use Ecto.Schema

  import Ecto.Changeset

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

  schema "commercial_samples" do
    belongs_to :link, Microwaveprop.Commercial.Link
    field :sampled_at, :utc_datetime_usec

    # Local radio
    field :rx_power_0, :float
    field :rx_power_1, :float
    field :tx_power, :float
    field :tx_freq_mhz, :integer
    field :rx_freq_mhz, :integer
    field :radio_temp_0_c, :float
    field :radio_temp_1_c, :float

    # Modulation & capacity
    field :cur_tx_mod_rate, :integer
    field :remote_tx_mod_rate, :integer
    field :rx_capacity, :integer
    field :tx_capacity, :integer

    # Remote radio
    field :remote_tx_power, :float
    field :remote_rx_power_0, :float
    field :remote_rx_power_1, :float

    # Link status
    field :link_state, :integer
    field :link_uptime, :integer
    field :link_distance_m, :integer

    timestamps(type: :utc_datetime)
  end

  @type t :: %__MODULE__{}

  @required_fields ~w(link_id sampled_at)a
  @optional_fields ~w(rx_power_0 rx_power_1 tx_power tx_freq_mhz rx_freq_mhz
    radio_temp_0_c radio_temp_1_c cur_tx_mod_rate remote_tx_mod_rate
    rx_capacity tx_capacity remote_tx_power remote_rx_power_0 remote_rx_power_1
    link_state link_uptime link_distance_m)a

  @spec changeset(t() | Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
  def changeset(sample, attrs) do
    sample
    |> cast(attrs, @required_fields ++ @optional_fields)
    |> validate_required(@required_fields)
    |> foreign_key_constraint(:link_id)
  end
end
