package http

import (
	"context"
	"encoding/json"
	stdhttp "net/http"
	"testing"
	"time"

	"github.com/oklog/ulid/v2"

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

func TestAPIAlertsListsOpen(t *testing.T) {
	t.Parallel()
	srv, ts, st := rawTestServer(t)
	hostID, _ := enrolHostForWS(t, srv, st, "host-alerts")
	_, _, _ = st.RaiseOrTouch(context.Background(), hostID,
		"backup_failed", "", "warning", "x", time.Now().UTC())
	cookie := loginAsAdmin(t, st)

	req, _ := stdhttp.NewRequest("GET", ts.URL+"/api/alerts?status=open", nil)
	req.AddCookie(cookie)
	res, err := stdhttp.DefaultClient.Do(req)
	if err != nil {
		t.Fatalf("do: %v", err)
	}
	defer res.Body.Close()
	if res.StatusCode != 200 {
		t.Fatalf("status: %d", res.StatusCode)
	}
	var got []store.Alert
	if err := json.NewDecoder(res.Body).Decode(&got); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if len(got) != 1 || got[0].Kind != "backup_failed" {
		t.Fatalf("got %+v", got)
	}
	_ = ulid.Make() // import keep
}
