defmodule Berrypod.Orders.AbandonedCartPruneWorker do
  @moduledoc """
  Nightly cron job that deletes abandoned cart records older than 30 days.

  After 30 days the recovery window is well past. Pruning keeps the table
  small and avoids retaining customer email addresses indefinitely.
  """

  use Oban.Worker, queue: :checkout

  import Ecto.Query

  alias Berrypod.Orders.AbandonedCart
  alias Berrypod.Repo

  require Logger

  @impl Oban.Worker
  def perform(_job) do
    cutoff = DateTime.add(DateTime.utc_now(), -30, :day)
    {count, _} = Repo.delete_all(from a in AbandonedCart, where: a.inserted_at < ^cutoff)
    Logger.info("Pruned #{count} abandoned cart records older than 30 days")
    :ok
  end
end
