defmodule Berrypod.Newsletter.CleanupWorker do
  @moduledoc """
  Prunes unconfirmed newsletter subscribers older than 48 hours.

  Runs daily via cron. Pending signups that never confirmed are deleted
  to keep the subscriber list clean and respect data minimisation.
  """

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

  import Ecto.Query

  alias Berrypod.Newsletter.Subscriber
  alias Berrypod.Repo

  require Logger

  @hours_to_expire 48

  @impl Oban.Worker
  def perform(%Oban.Job{}) do
    cutoff =
      DateTime.utc_now()
      |> DateTime.add(-@hours_to_expire * 3600)
      |> DateTime.truncate(:second)

    {count, _} =
      from(s in Subscriber,
        where: s.status == "pending" and s.inserted_at < ^cutoff
      )
      |> Repo.delete_all()

    if count > 0 do
      Logger.info("Newsletter cleanup: pruned #{count} unconfirmed subscribers")
    end

    :ok
  end
end
