defmodule Towerops.Gaiia.InventoryItem do
  @moduledoc """
  Schema for inventory items (deployed equipment) synced from Gaiia API.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  schema "gaiia_inventory_items" do
    field :gaiia_id, :string
    field :name, :string
    field :status, :string
    field :serial_number, :string
    field :mac_address, :string
    field :ip_address, :string
    field :model_name, :string
    field :manufacturer_name, :string
    field :category, :string
    field :assigned_account_gaiia_id, :string
    field :assigned_network_site_gaiia_id, :string
    field :raw_data, :map

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

    timestamps(type: :utc_datetime)
  end

  def changeset(inventory_item, attrs) do
    inventory_item
    |> cast(attrs, [
      :organization_id,
      :gaiia_id,
      :name,
      :status,
      :serial_number,
      :mac_address,
      :ip_address,
      :model_name,
      :manufacturer_name,
      :category,
      :assigned_account_gaiia_id,
      :assigned_network_site_gaiia_id,
      :device_id,
      :raw_data
    ])
    |> validate_required([:organization_id, :gaiia_id])
    |> unique_constraint([:organization_id, :gaiia_id],
      error_key: :gaiia_id,
      message: "has already been taken"
    )
    |> foreign_key_constraint(:organization_id)
    |> foreign_key_constraint(:device_id)
  end
end
