package controller

import (
	"errors"
	"net"
	"net/http"
	"testing"
	"time"
)

func Test_httpApi(t *testing.T) {
	tests := []struct {
		name    string
		request string
		want    *http.Response
		wantErr bool
	}{
		{
			name:    "/livez",
			request: apiEndpoint + "/livez",
			want:    &http.Response{StatusCode: http.StatusOK},
			wantErr: false,
		},
		{
			name:    "/readyz",
			request: apiEndpoint + "/readyz",
			want:    &http.Response{StatusCode: http.StatusOK},
			wantErr: false,
		},
		{
			name:    "/metrics",
			request: apiEndpoint + "/metrics",
			want:    &http.Response{StatusCode: http.StatusOK},
			wantErr: false,
		},
	}
	coreLock.Lock()
	startHttpServer()
	coreLock.Unlock()

	err := waitForHTTPServer()
	if err != nil {
		t.Errorf("httpApi() error = %v", err)
		return
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := http.Get(tt.request)
			if (err != nil) != tt.wantErr {
				t.Errorf("httpApi() error = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if got.StatusCode != tt.want.StatusCode {
				t.Errorf("httpApi() got: %v, want %v", got.StatusCode, tt.want.StatusCode)
			}
		})
	}
}

// see: https://stackoverflow.com/a/56865986
func waitForHTTPServer() error {
	for i := 0; i < 10; i++ {
		conn, err := net.DialTimeout("tcp", ":8080", 1*time.Second)
		if err != nil {
			time.Sleep(50 * time.Millisecond)
			continue
		}
		err = conn.Close()
		if err != nil {
			return err
		}
		return nil
	}
	return errors.New("http server could not be reached")
}
