//go:build test

package main

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"crussell/db"
)

func TestHealthCheck_OK(t *testing.T) {

	// Create request and recorder
	req := httptest.NewRequest(http.MethodGet, "/api/health", nil)
	w := httptest.NewRecorder()

	// Call handler directly
	healthCheckHandler(w, req)

	// Assert 200 OK
	if w.Code != http.StatusOK {
		t.Errorf("expected status %d, got %d. body: %s", http.StatusOK, w.Code, w.Body.String())
	}

	// Parse JSON response
	var response map[string]interface{}
	if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
		t.Fatalf("failed to parse JSON response: %v", err)
	}

	// Assert status == "ok"
	status, ok := response["status"].(string)
	if !ok || status != "ok" {
		t.Errorf("expected status 'ok', got '%v'", response["status"])
	}

	// Assert services
	services, ok := response["services"].(map[string]interface{})
	if !ok {
		t.Fatalf("services not found in response")
	}

	// Assert services.backend == "ok"
	backend, ok := services["backend"].(string)
	if !ok || backend != "ok" {
		t.Errorf("expected services.backend 'ok', got '%v'", services["backend"])
	}

	// Assert services.database == "ok"
	database, ok := services["database"].(string)
	if !ok || database != "ok" {
		t.Errorf("expected services.database 'ok', got '%v'", services["database"])
	}
}

func TestHealthCheck_Degraded(t *testing.T) {

	// Set db.Conn to nil to simulate degraded state
	originalDB := db.Conn
	db.Conn = nil

	// Create request and recorder
	req := httptest.NewRequest(http.MethodGet, "/api/health", nil)
	w := httptest.NewRecorder()

	// Call handler directly
	healthCheckHandler(w, req)

	// Assert 503 Service Unavailable
	if w.Code != http.StatusServiceUnavailable {
		t.Errorf("expected status %d, got %d. body: %s", http.StatusServiceUnavailable, w.Code, w.Body.String())
	}

	// Parse JSON response
	var response map[string]interface{}
	if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
		t.Fatalf("failed to parse JSON response: %v", err)
	}

	// Assert status == "degraded"
	status, ok := response["status"].(string)
	if !ok || status != "degraded" {
		t.Errorf("expected status 'degraded', got '%v'", response["status"])
	}

	// Assert services
	services, ok := response["services"].(map[string]interface{})
	if !ok {
		t.Fatalf("services not found in response")
	}

	// Assert services.database == "error"
	database, ok := services["database"].(string)
	if !ok || database != "error" {
		t.Errorf("expected services.database 'error', got '%v'", services["database"])
	}

	// Restore original db.Conn
	db.Conn = originalDB
}
