package main

import (
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func TestHealthcheckCmd_Success(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/healthz" {
			t.Errorf("unexpected path: %q", r.URL.Path)
		}
		w.WriteHeader(http.StatusOK)
	}))
	defer server.Close()

	cmd := newHealthcheckCmd()
	cmd.SetArgs([]string{"--port", serverPort(server)})
	if err := cmd.Execute(); err != nil {
		t.Fatalf("healthcheck failed: %v", err)
	}
}

func TestHealthcheckCmd_Failure(t *testing.T) {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(http.StatusServiceUnavailable)
	}))
	defer server.Close()

	cmd := newHealthcheckCmd()
	cmd.SetArgs([]string{"--port", serverPort(server)})
	err := cmd.Execute()
	if err == nil {
		t.Fatal("expected error for non-OK health status")
	}
}

func serverPort(server *httptest.Server) string {
	return server.Listener.Addr().String()[strings.LastIndex(server.Listener.Addr().String(), ":")+1:]
}
