package http

import (
	"context"
	"io"
	stdhttp "net/http"
	"strings"
	"testing"
	"time"

	"gitea.dcglab.co.uk/steve/restic-manager/internal/store"
)

func TestUIHostJobs_RendersList(t *testing.T) {
	t.Parallel()
	_, baseURL, st := newTestServerWithUI(t)
	cookie := loginAsAdmin(t, st)
	hostID := makeHost(t, st, "h-jobs-render")

	// Two jobs with distinct kinds + statuses.
	now := time.Now().UTC()
	ctx := context.Background()
	if err := st.CreateJob(ctx, store.Job{
		ID: "01HZZZZZZZZZZZZZZZZZZZZZ10", HostID: hostID, Kind: "backup",
		ActorKind: "user", CreatedAt: now.Add(-time.Hour),
	}); err != nil {
		t.Fatalf("create job: %v", err)
	}
	if err := st.MarkJobFinished(ctx, "01HZZZZZZZZZZZZZZZZZZZZZ10", "succeeded", 0, nil, "", now.Add(-time.Hour+time.Minute)); err != nil {
		t.Fatalf("finish job: %v", err)
	}
	if err := st.CreateJob(ctx, store.Job{
		ID: "01HZZZZZZZZZZZZZZZZZZZZZ11", HostID: hostID, Kind: "prune",
		ActorKind: "schedule", CreatedAt: now,
	}); err != nil {
		t.Fatalf("create job: %v", err)
	}
	if err := st.MarkJobFinished(ctx, "01HZZZZZZZZZZZZZZZZZZZZZ11", "failed", 1, nil, "boom", now.Add(time.Minute)); err != nil {
		t.Fatalf("finish job: %v", err)
	}

	body := getHostJobsPage(t, baseURL, hostID, cookie)
	for _, want := range []string{"backup", "prune", "succeeded", "failed", "schedule", "user", `class="jobs-row`} {
		if !strings.Contains(body, want) {
			t.Errorf("expected %q in body, missing", want)
		}
	}
}

func TestUIHostJobs_EmptyState(t *testing.T) {
	t.Parallel()
	_, baseURL, st := newTestServerWithUI(t)
	cookie := loginAsAdmin(t, st)
	hostID := makeHost(t, st, "h-jobs-empty")

	body := getHostJobsPage(t, baseURL, hostID, cookie)
	if !strings.Contains(body, "No jobs yet.") {
		t.Error("expected empty-state heading")
	}
}

// getHostJobsPage fetches /hosts/{id}/jobs and returns the body string.
func getHostJobsPage(t *testing.T, baseURL, hostID string, cookie *stdhttp.Cookie) string {
	t.Helper()
	client := &stdhttp.Client{
		CheckRedirect: func(_ *stdhttp.Request, _ []*stdhttp.Request) error {
			return stdhttp.ErrUseLastResponse
		},
	}
	req, err := stdhttp.NewRequest("GET", baseURL+"/hosts/"+hostID+"/jobs", nil)
	if err != nil {
		t.Fatalf("new request: %v", err)
	}
	req.AddCookie(cookie)
	res, err := client.Do(req)
	if err != nil {
		t.Fatalf("GET /hosts/%s/jobs: %v", hostID, err)
	}
	defer res.Body.Close()
	if res.StatusCode != stdhttp.StatusOK {
		t.Fatalf("GET /hosts/%s/jobs: want 200, got %d", hostID, res.StatusCode)
	}
	raw, _ := io.ReadAll(res.Body)
	return string(raw)
}
