defmodule Tarakan.Infestations.Swarm do
  @moduledoc """
  One recorded swarm run over an infestation pattern.

  Exists so the per-pattern cooldown has something exact to read. The obvious
  alternative - deriving "when was this pattern last swarmed" from the jobs
  themselves - has no honest key: `ReviewTask.target_code_pattern_key` is the
  code-cluster namespace used by `synthesize_rule`, not the infestation
  `pattern_key`, and matching on generated job titles would be guesswork.
  """

  use Ecto.Schema
  import Ecto.Changeset

  schema "infestation_swarms" do
    field :pattern_key, :string
    field :jobs_opened, :integer, default: 0
    field :candidates_seen, :integer, default: 0

    belongs_to :account, Tarakan.Accounts.Account

    timestamps(type: :utc_datetime_usec)
  end

  @doc false
  def changeset(swarm, attrs) do
    swarm
    |> cast(attrs, [:pattern_key, :jobs_opened, :candidates_seen, :account_id])
    |> validate_required([:pattern_key])
    |> validate_number(:jobs_opened, greater_than_or_equal_to: 0)
    |> validate_number(:candidates_seen, greater_than_or_equal_to: 0)
  end
end
