defmodule MicrowavepropWeb.HealthControllerTest do
  use MicrowavepropWeb.ConnCase, async: true

  alias Ecto.Adapters.SQL

  test "GET /health returns 200 ok", %{conn: conn} do
    conn = get(conn, "/health")

    assert response(conn, 200) == "ok"
    assert response_content_type(conn, :text) =~ "text/plain"
  end

  test "GET /live returns 200 ok", %{conn: conn} do
    conn = get(conn, "/live")

    assert response(conn, 200) == "ok"
    assert response_content_type(conn, :text) =~ "text/plain"
  end

  # The split between /live and /health is the load-bearing detail of
  # the production liveness fix. If the Ecto pool is saturated, /health
  # must fail (so readiness drains the pod) while /live must succeed
  # (so the kubelet doesn't SIGKILL the BEAM). Invoke the controller
  # actions without any Ecto sandbox assignment so the DB-touching path
  # is forced to raise — /live must not raise, /health must.
  describe "DB dependency" do
    test "live/2 returns 200 without touching the Repo", %{conn: conn} do
      # No `Ecto.Adapters.SQL.Sandbox.checkout` has been issued for this
      # test process in the async: true block, so any attempt to reach
      # the Repo would raise `DBConnection.OwnershipError`. A clean 200
      # proves the action never tried.
      refute conn.assigns[:ecto_sandbox]
      conn = MicrowavepropWeb.HealthController.live(conn, %{})
      assert conn.status == 200
      assert conn.resp_body == "ok"
    end

    test "check/2 issues a Repo query (proves it's the DB-gated endpoint)", %{conn: conn} do
      conn = get(conn, "/health")
      assert response(conn, 200) == "ok"
      assert {:ok, %{rows: [[1]]}} = SQL.query(Microwaveprop.Repo, "SELECT 1")
    end
  end
end
