package handlers

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

	"qctextbuilder/internal/logging"
)

func TestListLogsHonorsLimit(t *testing.T) {
	t.Parallel()

	recent := logging.NewRecentStore(10)
	recent.Add(logging.Entry{Timestamp: time.Now().UTC(), Level: "INFO", Message: "older"})
	recent.Add(logging.Entry{Timestamp: time.Now().UTC(), Level: "INFO", Message: "newer"})

	api := NewAPI(nil, nil, nil, nil, recent)
	req := httptest.NewRequest(http.MethodGet, "/api/logs?limit=1", nil)
	w := httptest.NewRecorder()

	api.ListLogs(w, req)
	if w.Code != http.StatusOK {
		t.Fatalf("unexpected status: %d", w.Code)
	}

	var payload struct {
		Count int             `json:"count"`
		Logs  []logging.Entry `json:"logs"`
	}
	if err := json.Unmarshal(w.Body.Bytes(), &payload); err != nil {
		t.Fatalf("decode response: %v", err)
	}
	if payload.Count != 1 || len(payload.Logs) != 1 {
		t.Fatalf("unexpected payload: %+v", payload)
	}
	if payload.Logs[0].Message != "newer" {
		t.Fatalf("expected newest log entry, got %q", payload.Logs[0].Message)
	}
}
