defmodule Berrypod.Newsletter.CleanupWorkerTest do
  use Berrypod.DataCase, async: true
  use Oban.Testing, repo: Berrypod.Repo

  alias Berrypod.Newsletter.{CleanupWorker, Subscriber}
  alias Berrypod.Repo

  import Berrypod.NewsletterFixtures

  describe "perform/1" do
    test "prunes pending subscribers older than 48 hours" do
      # Insert an old pending subscriber directly
      old_time = DateTime.utc_now() |> DateTime.add(-49 * 3600) |> DateTime.truncate(:second)

      %Subscriber{}
      |> Subscriber.changeset(%{email: "old@example.com", status: "pending"})
      |> Ecto.Changeset.force_change(:inserted_at, old_time)
      |> Repo.insert!()

      # Insert a fresh pending subscriber
      %Subscriber{}
      |> Subscriber.changeset(%{email: "fresh@example.com", status: "pending"})
      |> Repo.insert!()

      assert :ok = perform_job(CleanupWorker, %{})

      # Old pending subscriber should be deleted
      assert Repo.get_by(Subscriber, email: "old@example.com") == nil
      # Fresh one should remain
      assert Repo.get_by(Subscriber, email: "fresh@example.com") != nil
    end

    test "does not prune confirmed subscribers" do
      old_time = DateTime.utc_now() |> DateTime.add(-49 * 3600) |> DateTime.truncate(:second)

      confirmed = confirmed_subscriber_fixture(email: "confirmed@example.com")

      # Backdate the subscriber
      confirmed
      |> Ecto.Changeset.change(inserted_at: old_time)
      |> Repo.update!()

      assert :ok = perform_job(CleanupWorker, %{})

      assert Repo.get_by(Subscriber, email: "confirmed@example.com") != nil
    end
  end
end
