defmodule Towerops.Gaiia.Account do
  @moduledoc """
  Schema for subscriber accounts synced from Gaiia API.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  schema "gaiia_accounts" do
    field :gaiia_id, :string
    field :readable_id, :string
    field :name, :string
    field :status, :string
    field :account_type, :string
    field :address, :map
    field :subscription_count, :integer
    field :mrr, :decimal
    field :raw_data, :map

    belongs_to :organization, Towerops.Organizations.Organization

    timestamps(type: :utc_datetime)
  end

  def changeset(account, attrs) do
    account
    |> cast(attrs, [
      :organization_id,
      :gaiia_id,
      :readable_id,
      :name,
      :status,
      :account_type,
      :address,
      :subscription_count,
      :mrr,
      :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)
  end
end
