defmodule Microwaveprop.BeaconMonitors.BeaconMonitor do
  @moduledoc """
  A beacon monitor is a remote station running the monitor program
  that reports beacon reception data. Each monitor is owned by a user
  and identified by a random token the program uses to authenticate.
  """

  use Ecto.Schema

  import Ecto.Changeset

  alias Microwaveprop.Accounts.User

  @primary_key {:id, :binary_id, autogenerate: true}
  @foreign_key_type :binary_id
  schema "beacon_monitors" do
    field :name, :string
    field :token, :string
    field :last_seen_at, :utc_datetime

    belongs_to :user, User

    timestamps(type: :utc_datetime)
  end

  @type t :: %__MODULE__{}

  @doc """
  Changeset for user-controlled fields (name only for now).
  Token and user_id are assigned by the context, not cast from user input.
  """
  @spec changeset(t() | Ecto.Changeset.t(), map()) :: Ecto.Changeset.t()
  def changeset(monitor, attrs) do
    monitor
    |> cast(attrs, [:name])
    |> validate_required([:name])
    |> validate_length(:name, min: 1, max: 100)
  end
end
