defmodule Berrypod.Analytics.RetentionWorkerTest do
  use Berrypod.DataCase, async: false

  alias Berrypod.Analytics.{Event, RetentionWorker}
  alias Berrypod.Repo

  setup do
    Repo.delete_all(Event)
    :ok
  end

  test "deletes events older than 12 months" do
    old = DateTime.add(DateTime.utc_now(), -400, :day) |> DateTime.truncate(:second)
    recent = DateTime.utc_now() |> DateTime.truncate(:second)

    Repo.insert_all(Event, [
      [
        id: Ecto.UUID.generate(),
        name: "pageview",
        pathname: "/old",
        visitor_hash: :crypto.strong_rand_bytes(8),
        session_hash: :crypto.strong_rand_bytes(8),
        inserted_at: old
      ],
      [
        id: Ecto.UUID.generate(),
        name: "pageview",
        pathname: "/recent",
        visitor_hash: :crypto.strong_rand_bytes(8),
        session_hash: :crypto.strong_rand_bytes(8),
        inserted_at: recent
      ]
    ])

    assert :ok = RetentionWorker.perform(%Oban.Job{})

    events = Repo.all(Event)
    assert length(events) == 1
    assert hd(events).pathname == "/recent"
  end

  test "no-op when no old events exist" do
    assert :ok = RetentionWorker.perform(%Oban.Job{})
  end
end
