package httpserver_test

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

	httpserver "bit.admedia.com/scm/ad/adpilot-indexing-repo-sync.com/internal/http"
)

func TestHealthEndpoints(t *testing.T) {
	server := httpserver.New("repo-sync-service", func() bool { return true }, nil, nil, nil, nil, nil, nil, "")

	tests := []struct {
		name       string
		path       string
		wantStatus int
	}{
		{name: "root", path: "/", wantStatus: http.StatusOK},
		{name: "healthz", path: "/healthz", wantStatus: http.StatusOK},
		{name: "readyz", path: "/readyz", wantStatus: http.StatusOK},
		{name: "version", path: "/version", wantStatus: http.StatusOK},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := httptest.NewRequest(http.MethodGet, tt.path, nil)
			rec := httptest.NewRecorder()
			server.Handler().ServeHTTP(rec, req)

			if rec.Code != tt.wantStatus {
				t.Fatalf("expected status %d, got %d", tt.wantStatus, rec.Code)
			}
		})
	}
}

func TestReadyzNotReady(t *testing.T) {
	server := httpserver.New("repo-sync-service", func() bool { return false }, nil, nil, nil, nil, nil, nil, "")

	req := httptest.NewRequest(http.MethodGet, "/readyz", nil)
	rec := httptest.NewRecorder()
	server.Handler().ServeHTTP(rec, req)

	if rec.Code != http.StatusServiceUnavailable {
		t.Fatalf("expected status %d, got %d", http.StatusServiceUnavailable, rec.Code)
	}
}

func TestRegisteredRoutesSmoke(t *testing.T) {
	trigger := &mockSyncTrigger{jobID: "job_smoke123"}
	metadata := &mockMetadataReader{}
	webhook := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.WriteHeader(http.StatusAccepted)
	})
	server := httpserver.New("repo-sync-service", func() bool { return true }, trigger, nil, nil, metadata, nil, webhook, "")

	tests := []struct {
		name       string
		method     string
		path       string
		wantStatus int
	}{
		{name: "admin sync wrong method", method: http.MethodGet, path: "/admin/repos/ad%2Fexample-repo/sync", wantStatus: http.StatusMethodNotAllowed},
		{name: "repos wrong method", method: http.MethodPost, path: "/repos/ad%2Fexample-repo", wantStatus: http.StatusMethodNotAllowed},
		{name: "snapshot wrong method", method: http.MethodPost, path: "/repos/ad%2Fexample-repo/snapshots/snap_01", wantStatus: http.StatusMethodNotAllowed},
		{name: "webhook wrong method", method: http.MethodGet, path: "/webhooks/bitbucket", wantStatus: http.StatusMethodNotAllowed},
		{name: "unknown route", method: http.MethodGet, path: "/unknown", wantStatus: http.StatusNotFound},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := httptest.NewRequest(tt.method, tt.path, nil)
			rec := httptest.NewRecorder()
			server.Handler().ServeHTTP(rec, req)

			if rec.Code != tt.wantStatus {
				t.Fatalf("expected status %d, got %d body=%s", tt.wantStatus, rec.Code, rec.Body.String())
			}
		})
	}
}
