defmodule Microwaveprop.Workers.GridCachePruneWorkerTest do
  use ExUnit.Case, async: false

  alias Microwaveprop.Weather.GridCache
  alias Microwaveprop.Workers.GridCachePruneWorker

  setup do
    GridCache.clear()
    :ok
  end

  describe "perform/1" do
    test "removes cache entries with valid_time older than 3 hours" do
      now = DateTime.utc_now()
      old = now |> DateTime.add(-3, :hour) |> DateTime.add(-1, :second) |> DateTime.truncate(:second)
      fresh = now |> DateTime.add(-30, :minute) |> DateTime.truncate(:second)
      future = now |> DateTime.add(6, :hour) |> DateTime.truncate(:second)

      GridCache.put(old, [%{lat: 32.0, lon: -97.0, temperature: 10.0}])
      GridCache.put(fresh, [%{lat: 32.0, lon: -97.0, temperature: 20.0}])
      GridCache.put(future, [%{lat: 32.0, lon: -97.0, temperature: 30.0}])

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

      assert GridCache.fetch(old) == :miss
      assert {:ok, [%{temperature: 20.0}]} = GridCache.fetch(fresh)
      assert {:ok, [%{temperature: 30.0}]} = GridCache.fetch(future)
    end

    test "is a no-op when nothing is stale" do
      fresh =
        DateTime.utc_now() |> DateTime.add(-30, :minute) |> DateTime.truncate(:second)

      GridCache.put(fresh, [%{lat: 32.0, lon: -97.0, temperature: 42.0}])

      assert :ok = GridCachePruneWorker.perform(%Oban.Job{})
      assert {:ok, [%{temperature: 42.0}]} = GridCache.fetch(fresh)
    end
  end
end
