defmodule Microwaveprop.GeocoderTest do
  use ExUnit.Case, async: true

  alias Microwaveprop.Geocoder

  describe "geocode/1" do
    test "returns lat/lon for a valid address" do
      Req.Test.expect(Geocoder, fn conn ->
        conn
        |> Plug.Conn.put_resp_content_type("application/json")
        |> Plug.Conn.send_resp(
          200,
          Jason.encode!(%{
            "status" => "OK",
            "results" => [%{"geometry" => %{"location" => %{"lat" => 41.714775, "lng" => -72.727260}}}]
          })
        )
      end)

      assert {:ok, %{lat: 41.714775, lon: -72.727260}} =
               Geocoder.geocode("225 Main St, Newington, CT 06111")
    end

    test "returns error when no results found" do
      Req.Test.expect(Geocoder, fn conn ->
        conn
        |> Plug.Conn.put_resp_content_type("application/json")
        |> Plug.Conn.send_resp(200, Jason.encode!(%{"status" => "ZERO_RESULTS", "results" => []}))
      end)

      assert {:error, "No results found"} = Geocoder.geocode("xyzzy nowhere land")
    end

    test "returns error on API failure" do
      Req.Test.expect(Geocoder, fn conn ->
        conn
        |> Plug.Conn.put_resp_content_type("application/json")
        |> Plug.Conn.send_resp(
          200,
          Jason.encode!(%{"status" => "REQUEST_DENIED", "error_message" => "Invalid API key"})
        )
      end)

      assert {:error, "Geocoding failed: REQUEST_DENIED"} = Geocoder.geocode("test")
    end

    test "returns error when request fails" do
      Req.Test.expect(Geocoder, &Req.Test.transport_error(&1, :timeout))

      assert {:error, "Geocoding request failed: " <> _} = Geocoder.geocode("test")
    end
  end
end
