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

  describe "GET /health" do
    test "returns ok with database and redis connectivity check", %{conn: conn} do
      conn = get(conn, ~p"/health")

      response = json_response(conn, 200)

      assert response["status"] == "ok"
      assert response["database"] == "connected"
      # Redis may be "connected" or "not_configured" depending on environment
      assert response["redis"] in ["connected", "not_configured"]
      assert response["version"] == "0.1.0"

      assert get_resp_header(conn, "content-type") == ["application/json; charset=utf-8"]
    end
  end

  describe "GET /health/time" do
    test "returns server time from multiple sources", %{conn: conn} do
      conn = get(conn, ~p"/health/time")

      response = json_response(conn, 200)

      # Verify all expected fields are present
      assert Map.has_key?(response, "system_time")
      assert Map.has_key?(response, "system_time_iso")
      assert Map.has_key?(response, "os_time")
      assert Map.has_key?(response, "os_time_iso")
      assert Map.has_key?(response, "datetime_now")
      assert Map.has_key?(response, "datetime_now_iso")
      assert Map.has_key?(response, "time_sources_agree")

      # Verify types
      assert is_integer(response["system_time"])
      assert is_binary(response["system_time_iso"])
      assert is_integer(response["os_time"])
      assert is_binary(response["os_time_iso"])
      assert is_integer(response["datetime_now"])
      assert is_binary(response["datetime_now_iso"])
      assert is_boolean(response["time_sources_agree"])

      # Verify ISO 8601 format
      assert String.match?(response["system_time_iso"], ~r/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)
      assert String.match?(response["os_time_iso"], ~r/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)
      assert String.match?(response["datetime_now_iso"], ~r/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)

      # Verify all times are within a reasonable range (within 5 seconds of each other)
      time_diff_1 = abs(response["system_time"] - response["os_time"])
      time_diff_2 = abs(response["system_time"] - response["datetime_now"])

      assert time_diff_1 <= 5, "system_time and os_time should be within 5 seconds"
      assert time_diff_2 <= 5, "system_time and datetime_now should be within 5 seconds"

      assert get_resp_header(conn, "content-type") == ["application/json; charset=utf-8"]
    end
  end
end
