defmodule Towerops.Profiles.DeviceProfile do
  @moduledoc """
  Schema for device profiles stored in database.
  Profiles define how to identify and discover sensors for different device types.
  """

  use Ecto.Schema

  import Ecto.Changeset

  alias Towerops.Profiles.DeviceOid
  alias Towerops.Profiles.SensorOid

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

  schema "device_profiles" do
    field :name, :string
    field :vendor, :string
    field :detection_pattern, :string
    field :detection_oid, :string
    field :priority, :integer, default: 100
    field :enabled, :boolean, default: true

    has_many :device_oids, DeviceOid, foreign_key: :profile_id
    has_many :sensor_oids, SensorOid, foreign_key: :profile_id

    timestamps(type: :utc_datetime)
  end

  def changeset(profile, attrs) do
    profile
    |> cast(attrs, [:name, :vendor, :detection_pattern, :detection_oid, :priority, :enabled])
    |> validate_required([:name, :vendor])
    |> unique_constraint(:name)
  end
end
