defmodule Towerops.JobsFixtures do
  @moduledoc """
  This module defines test helpers for creating Oban jobs for testing.
  """

  alias Towerops.Repo

  @doc """
  Generate an Oban job with all required fields.
  """
  def oban_job_fixture(attrs \\ %{}) do
    default_attrs = %{
      worker: "Towerops.Workers.DevicePollerWorker",
      queue: "pollers",
      args: %{"device_id" => 1},
      state: "available",
      attempt: 0,
      max_attempts: 3,
      inserted_at: DateTime.utc_now(),
      scheduled_at: DateTime.utc_now()
    }

    merged_attrs =
      Map.merge(
        default_attrs,
        Map.new(attrs, fn {k, v} -> {to_atom_key(k), v} end)
      )

    job = struct!(Oban.Job, merged_attrs)
    Repo.insert!(job)
  end

  defp to_atom_key(key) when is_atom(key), do: key
  defp to_atom_key(key) when is_binary(key), do: String.to_existing_atom(key)
end
