package handlers

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

	"github.com/gofiber/fiber/v2"

	"wucher/internal/buildinfo"
)

func TestNewBuildInfoHandler(t *testing.T) {
	h := NewBuildInfoHandler()
	if h == nil {
		t.Fatalf("expected build info handler instance")
	}
}

func TestBuildInfoHandler_Handle(t *testing.T) {
	origVersion := buildinfo.Version
	origCommit := buildinfo.Commit
	origBuildTime := buildinfo.BuildTime
	t.Cleanup(func() {
		buildinfo.Version = origVersion
		buildinfo.Commit = origCommit
		buildinfo.BuildTime = origBuildTime
	})

	buildinfo.Version = "dev"
	buildinfo.Commit = "unknown"
	buildinfo.BuildTime = "unknown"

	h := NewBuildInfoHandler()
	app := fiber.New()
	app.Get("/api/build-info", h.Handle)

	req, _ := http.NewRequest(http.MethodGet, "/api/build-info", nil)
	resp, err := app.Test(req)
	if err != nil {
		t.Fatalf("app.Test: %v", err)
	}
	if resp.StatusCode != http.StatusOK {
		t.Fatalf("expected 200, got %d", resp.StatusCode)
	}

	var got map[string]string
	if err := json.NewDecoder(resp.Body).Decode(&got); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if got["version"] != "dev" {
		t.Fatalf("expected version dev, got %q", got["version"])
	}
	if got["commit"] != "unknown" {
		t.Fatalf("expected commit unknown, got %q", got["commit"])
	}
	if got["buildTime"] != "unknown" {
		t.Fatalf("expected buildTime unknown, got %q", got["buildTime"])
	}
}
