defmodule Berrypod.Shipping.ShippingRate do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "shipping_rates" do
    field :blueprint_id, :integer
    field :print_provider_id, :integer
    field :country_code, :string
    field :first_item_cost, :integer
    field :additional_item_cost, :integer
    field :currency, :string, default: "USD"
    field :handling_time_days, :integer

    belongs_to :provider_connection, Berrypod.Products.ProviderConnection

    timestamps(type: :utc_datetime)
  end

  def changeset(rate, attrs) do
    rate
    |> cast(attrs, [
      :provider_connection_id,
      :blueprint_id,
      :print_provider_id,
      :country_code,
      :first_item_cost,
      :additional_item_cost,
      :currency,
      :handling_time_days
    ])
    |> validate_required([
      :provider_connection_id,
      :blueprint_id,
      :print_provider_id,
      :country_code,
      :first_item_cost,
      :additional_item_cost,
      :currency
    ])
    |> validate_number(:first_item_cost, greater_than_or_equal_to: 0)
    |> validate_number(:additional_item_cost, greater_than_or_equal_to: 0)
    |> foreign_key_constraint(:provider_connection_id)
    |> unique_constraint([
      :provider_connection_id,
      :blueprint_id,
      :print_provider_id,
      :country_code
    ])
  end
end
