defmodule Berrypod.ActivityLog.Entry do
  use Ecto.Schema
  import Ecto.Changeset

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

  @levels ~w(info warning error)

  schema "activity_log" do
    field :event_type, :string
    field :level, :string, default: "info"
    field :order_id, :binary_id
    field :payload, :map, default: %{}
    field :message, :string
    field :resolved_at, :utc_datetime
    field :occurred_at, :utc_datetime

    timestamps(type: :utc_datetime)
  end

  def changeset(entry, attrs) do
    entry
    |> cast(attrs, [
      :event_type,
      :level,
      :order_id,
      :payload,
      :message,
      :resolved_at,
      :occurred_at
    ])
    |> validate_required([:event_type, :level, :message, :occurred_at])
    |> validate_inclusion(:level, @levels)
  end
end
