defmodule Berrypod.Newsletter.ConfirmationEmailWorkerTest do
  use Berrypod.DataCase, async: true
  use Oban.Testing, repo: Berrypod.Repo

  alias Berrypod.Newsletter.ConfirmationEmailWorker

  import Berrypod.NewsletterFixtures

  describe "perform/1" do
    test "sends confirmation email for pending subscriber" do
      # Create subscriber in manual mode so the confirmation job doesn't auto-run
      Oban.Testing.with_testing_mode(:manual, fn ->
        {:ok, sub} = Berrypod.Newsletter.subscribe("test@example.com")

        [job] = all_enqueued(worker: ConfirmationEmailWorker)
        raw_token = job.args["raw_token"]

        # Now perform the job (uses Swoosh.Adapters.Local in test)
        assert :ok =
                 perform_job(ConfirmationEmailWorker, %{
                   subscriber_id: sub.id,
                   raw_token: raw_token
                 })
      end)
    end

    test "skips if subscriber is no longer pending" do
      sub = confirmed_subscriber_fixture()

      assert :ok =
               perform_job(ConfirmationEmailWorker, %{
                 subscriber_id: sub.id,
                 raw_token: "irrelevant"
               })
    end

    test "cancels if subscriber not found" do
      assert {:cancel, :not_found} =
               perform_job(ConfirmationEmailWorker, %{
                 subscriber_id: Ecto.UUID.generate(),
                 raw_token: "irrelevant"
               })
    end
  end
end
