defmodule WhoNeedHelp.Trust.RateLimitBucket do
  use Ecto.Schema
  import Ecto.Changeset

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

  schema "rate_limit_buckets" do
    field :action, :string
    field :scope_hash, :binary
    field :window_started_at, :utc_datetime
    field :count, :integer, default: 0
    field :expires_at, :utc_datetime
    timestamps(type: :utc_datetime)
  end

  def changeset(bucket, attrs) do
    bucket
    |> cast(attrs, [:action, :scope_hash, :window_started_at, :count, :expires_at])
    |> validate_required([:action, :scope_hash, :window_started_at, :count, :expires_at])
    |> validate_length(:action, min: 1, max: 80)
    |> validate_number(:count, greater_than_or_equal_to: 0)
    |> unique_constraint([:action, :scope_hash, :window_started_at])
  end
end
