defmodule Towerops.Gaiia.BillingSubscription do
  @moduledoc """
  Schema for billing subscriptions synced from Gaiia API.
  """
  use Ecto.Schema

  import Ecto.Changeset

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

  schema "gaiia_billing_subscriptions" do
    field :gaiia_id, :string
    field :account_gaiia_id, :string
    field :status, :string
    field :product_name, :string
    field :mrr_amount, :decimal
    field :currency, :string
    field :speed_download, :integer
    field :speed_upload, :integer
    field :raw_data, :map

    belongs_to :organization, Towerops.Organizations.Organization

    timestamps(type: :utc_datetime)
  end

  def changeset(billing_subscription, attrs) do
    billing_subscription
    |> cast(attrs, [
      :organization_id,
      :gaiia_id,
      :account_gaiia_id,
      :status,
      :product_name,
      :mrr_amount,
      :currency,
      :speed_download,
      :speed_upload,
      :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
