package health

import (
	"context"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type mockOperator struct {
	mongoClient *mongo.Client
}

func (m *mockOperator) GetMongoDB() *mongo.Client {
	return m.mongoClient
}

func TestHealthChecks(t *testing.T) {
	// Create a real MongoDB client for testing
	client, err := mongo.Connect(context.Background(), options.Client().ApplyURI("mongodb://localhost:27017"))
	if err != nil {
		t.Skip("MongoDB not available:", err)
	}
	defer client.Disconnect(context.Background())

	mockOp := &mockOperator{
		mongoClient: client,
	}

	handler := &Handler{Operator: mockOp}

	t.Run("healthz", func(t *testing.T) {
		req := httptest.NewRequest(http.MethodGet, "/healthz", nil)
		w := httptest.NewRecorder()

		handler.Healthz(w, req)

		assert.Equal(t, http.StatusOK, w.Code)
	})

	t.Run("readyz", func(t *testing.T) {
		// Skip if MongoDB is not available
		ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
		defer cancel()
		if err := client.Ping(ctx, nil); err != nil {
			t.Skip("MongoDB not available:", err)
		}

		req := httptest.NewRequest(http.MethodGet, "/readyz", nil)
		w := httptest.NewRecorder()

		handler.Readyz(w, req)

		assert.Equal(t, http.StatusOK, w.Code)
	})
}
