/*
Copyright 2022 CAcert Inc.
SPDX-License-Identifier: Apache-2.0

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package handlers

import (
	"database/sql"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"path"
	"testing"
	"time"

	"github.com/jmoiron/sqlx"
	"github.com/lestrrat-go/tcputil"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"git.cacert.org/cacert-boardvoting/internal/notifications"

	"git.cacert.org/cacert-boardvoting/internal/models"
)

func StartTestTCPServer(t *testing.T) int {
	t.Helper()

	port, err := tcputil.EmptyPort()
	require.NoError(t, err)

	go func(port int) {
		l, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", port))
		if err != nil {
			t.Errorf("could not run test TCP listener: %v", err)
		}

		defer func(l net.Listener) {
			_ = l.Close()
		}(l)

		for {
			conn, err := l.Accept()

			if err != nil {
				t.Errorf("could not accept connection: %v", err)

				return
			}

			if err = conn.Close(); err != nil {
				t.Errorf("could not close connection: %v", err)
			}
		}
	}(port)

	return port
}

func TestHealthCheck_ServeHTTP(t *testing.T) {
	port := StartTestTCPServer(t)

	t.Run("check with valid DB", func(t *testing.T) {
		rr := httptest.NewRecorder()

		r, err := http.NewRequest(http.MethodGet, "/health", nil)
		require.NoError(t, err)

		testDB := prepareTestDb(t)

		notifier := notifications.NewMailNotifier(&notifications.MailConfig{
			SMTPHost:    "localhost",
			SMTPPort:    port,
			SMTPTimeOut: 1 * time.Second,
		})

		hc := NewHealthCheck(notifier, &models.MotionModel{DB: testDB})
		hc.ServeHTTP(rr, r)

		rs := rr.Result()

		defer func(Body io.Closer) { _ = Body.Close() }(rs.Body)

		assert.Equal(t, http.StatusOK, rs.StatusCode)
	})

	t.Run("check with broken DB", func(t *testing.T) {
		rr := httptest.NewRecorder()

		r, err := http.NewRequest(http.MethodGet, "/health", nil)
		require.NoError(t, err)

		testDir := t.TempDir()

		db, err := sql.Open("sqlite3", path.Join(testDir, "test.sqlite"))
		require.NoError(t, err)

		testDB := sqlx.NewDb(db, "sqlite3")

		_ = db.Close()

		notifier := notifications.NewMailNotifier(&notifications.MailConfig{
			SMTPHost:    "localhost",
			SMTPPort:    port,
			SMTPTimeOut: 1 * time.Second,
		})

		hc := NewHealthCheck(notifier, &models.MotionModel{DB: testDB})
		hc.ServeHTTP(rr, r)

		rs := rr.Result()

		defer func(Body io.Closer) { _ = Body.Close() }(rs.Body)

		assert.Equal(t, http.StatusInternalServerError, rs.StatusCode)
	})
}
