defmodule Towerops.Preseem.AccessPoint do
  @moduledoc """
  Schema for access points synced from Preseem API.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  @valid_match_confidences ~w(auto_mac auto_ip auto_hostname manual ambiguous unmatched)

  schema "preseem_access_points" do
    field :preseem_id, :string
    field :name, :string
    field :mac_address, :string
    field :ip_address, :string
    field :model, :string
    field :firmware, :string
    field :capacity_score, :float
    field :qoe_score, :float
    field :rf_score, :float
    field :busy_hours, :integer
    field :airtime_utilization, :float
    field :subscriber_count, :integer
    field :match_confidence, :string, default: "unmatched"
    field :raw_data, :map

    belongs_to :organization, Towerops.Organizations.Organization
    belongs_to :device, Towerops.Devices.Device

    timestamps(type: :utc_datetime)
  end

  def changeset(access_point, attrs) do
    access_point
    |> cast(attrs, [
      :organization_id,
      :preseem_id,
      :name,
      :mac_address,
      :ip_address,
      :model,
      :firmware,
      :capacity_score,
      :qoe_score,
      :rf_score,
      :busy_hours,
      :airtime_utilization,
      :subscriber_count,
      :device_id,
      :match_confidence,
      :raw_data
    ])
    |> validate_required([:organization_id, :preseem_id])
    |> validate_inclusion(:match_confidence, @valid_match_confidences)
    |> unique_constraint([:organization_id, :preseem_id],
      error_key: :preseem_id,
      message: "has already been taken"
    )
    |> foreign_key_constraint(:organization_id)
    |> foreign_key_constraint(:device_id)
  end
end
