defmodule Berrypod.Settings.Setting do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "settings" do
    field :key, :string
    field :value, :string
    field :value_type, :string, default: "string"
    field :encrypted_value, :binary

    timestamps(type: :utc_datetime)
  end

  @doc false
  def changeset(setting, attrs) do
    setting
    |> cast(attrs, [:key, :value, :value_type, :encrypted_value])
    |> validate_required([:key, :value_type])
    |> validate_inclusion(:value_type, ~w(string json integer boolean encrypted))
    |> validate_has_value()
    |> unique_constraint(:key)
  end

  # Encrypted settings store data in encrypted_value, not value.
  # All other types require value.
  defp validate_has_value(changeset) do
    case get_field(changeset, :value_type) do
      "encrypted" ->
        validate_required(changeset, [:encrypted_value])

      _ ->
        validate_required(changeset, [:value])
    end
  end
end
