defmodule Berrypod.Analytics.RetentionWorker do
  @moduledoc """
  Oban worker that deletes analytics events older than the retention period.

  Runs daily via cron. Default retention is 12 months.
  """

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

  alias Berrypod.Analytics

  @default_retention_months 12

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

    {deleted, _} = Analytics.delete_events_before(cutoff)

    if deleted > 0 do
      require Logger
      Logger.info("Analytics retention: deleted #{deleted} events older than #{cutoff}")
    end

    :ok
  end
end
