defmodule Berrypod.Newsletter.ConfirmationEmailWorker do
  @moduledoc """
  Sends the double opt-in confirmation email to a new subscriber.
  """

  use Oban.Worker, queue: :newsletter, max_attempts: 3

  alias Berrypod.Newsletter
  alias Berrypod.Newsletter.Notifier

  require Logger

  @impl Oban.Worker
  def perform(%Oban.Job{args: %{"subscriber_id" => id, "raw_token" => raw_token}}) do
    case Berrypod.Repo.get(Newsletter.Subscriber, id) do
      %{status: "pending"} = sub ->
        case Notifier.deliver_confirmation(sub, raw_token) do
          {:ok, _} ->
            Logger.info("Newsletter confirmation sent to #{sub.email}")
            :ok

          {:error, reason} ->
            Logger.error("Newsletter confirmation failed for #{sub.email}: #{inspect(reason)}")
            {:error, reason}
        end

      %{status: _other} ->
        Logger.info("Newsletter confirmation skipped: subscriber #{id} no longer pending")
        :ok

      nil ->
        Logger.warning("Newsletter confirmation: subscriber #{id} not found")
        {:cancel, :not_found}
    end
  end
end
