package health

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"github.com/fiskerinc/cloud-services/pkg/testhelper"
)

const (
	checkErr = "failed during RabbitMQ health check"
)

func TestRegisterWithNoName(t *testing.T) {
	h, err := New()
	testhelper.NoError(t, "New", err)

	err = h.Register(Config{
		Name: "",
		Check: func(context.Context) error {
			return nil
		},
	})
	testhelper.Error(t, "Register", err)
}

func TestDoubleRegister(t *testing.T) {
	h, err := New()
	testhelper.NoError(t, "New", err)

	healthCheckName := "health-check"

	conf := Config{
		Name: healthCheckName,
		Check: func(context.Context) error {
			return nil
		},
	}

	err = h.Register(conf)
	testhelper.NoError(t, "Register", err)

	err = h.Register(conf)
	testhelper.Error(t, "the second registration of a health check config should return an error, but did not", err)

	err = h.Register(Config{
		Name: healthCheckName,
		Check: func(context.Context) error {
			return errors.New("health checks registered")
		},
	})
	testhelper.Error(t, "registration with same name, but different details should still return an error, but did not", err)
}

func TestReadinessHandler(t *testing.T) {
	h, err := New()
	testhelper.NoError(t, "New", err)

	res := httptest.NewRecorder()
	req, err := http.NewRequest("GET", "http://localhost/readiness", nil)
	testhelper.NoError(t, "NewRequest", err)

	err = h.Register(Config{
		Name:      "rabbitmq",
		SkipOnErr: true,
		Check:     func(context.Context) error { return errors.New(checkErr) },
	})
	testhelper.NoError(t, "Register rabbitmq", err)

	err = h.Register(Config{
		Name:  "mongodb",
		Check: func(context.Context) error { return nil },
	})
	testhelper.NoError(t, "Register mongodb", err)

	err = h.Register(Config{
		Name:      "snail-service",
		SkipOnErr: true,
		Timeout:   time.Second * 1,
		Check: func(context.Context) error {
			time.Sleep(time.Second * 2)
			return nil
		},
	})
	testhelper.NoError(t, "Register snail-service", err)

	handler := h.ReadinessHandler()
	handler.ServeHTTP(res, req)

	testhelper.Equal(t, "status handler returned wrong status code", http.StatusOK, res.Code)

	body := make(map[string]interface{})
	err = json.NewDecoder(res.Body).Decode(&body)
	testhelper.NoError(t, "NewDecoder", err)

	testhelper.Equal(t, "body returned wrong status", string(StatusPartiallyAvailable), body["status"])

	failure, ok := body["failures"]
	testhelper.True(t, "body returned nil failures field", ok)

	f, ok := failure.(map[string]interface{})
	testhelper.True(t, "body returned nil failures.rabbitmq field", ok)

	testhelper.Equal(t, "body returned wrong status for rabbitmq", checkErr, f["rabbitmq"])
	testhelper.Equal(t, "body returned wrong status for snail-service", string(StatusTimeout), f["snail-service"])
}

func TestLivenessHandler(t *testing.T) {
	h, err := New()
	testhelper.NoError(t, "New", err)

	res := httptest.NewRecorder()
	req, err := http.NewRequest("GET", "http://localhost/liveness", nil)
	testhelper.NoError(t, "NewRequest", err)

	err = h.Register(Config{
		Name:      "rabbitmq",
		SkipOnErr: true,
		Check:     func(context.Context) error { return errors.New(checkErr) },
		Vital:     true,
	})
	testhelper.NoError(t, "Register rabbitmq", err)

	err = h.Register(Config{
		Name:  "mongodb",
		Check: func(context.Context) error { return nil },
	})
	testhelper.NoError(t, "Register mongodb", err)

	err = h.Register(Config{
		Name:      "snail-service",
		SkipOnErr: true,
		Timeout:   time.Second * 1,
		Check: func(context.Context) error {
			time.Sleep(time.Second * 2)
			return nil
		},
		Vital: true,
	})
	testhelper.NoError(t, "Register snail-service", err)

	handler := h.LivenessHandler()
	handler.ServeHTTP(res, req)

	testhelper.Equal(t, "status handler returned wrong status code", http.StatusOK, res.Code)

	body := make(map[string]interface{})
	err = json.NewDecoder(res.Body).Decode(&body)
	testhelper.NoError(t, "NewDecoder", err)

	testhelper.Equal(t, "body returned wrong status", string(StatusPartiallyAvailable), body["status"])

	failure, ok := body["failures"]
	testhelper.True(t, "body returned nil failures field", ok)

	f, ok := failure.(map[string]interface{})
	testhelper.True(t, "body returned nil failures.rabbitmq field", ok)

	testhelper.Equal(t, "body returned wrong status for rabbitmq", checkErr, f["rabbitmq"])
	testhelper.Equal(t, "body returned wrong status for snail-service", string(StatusTimeout), f["snail-service"])
}
