package http

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

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

func TestAPIUsersList(t *testing.T) {
	t.Parallel()
	srv, ts, _ := rawTestServerWithUI(t)
	adminID := makeUser(t, srv, "admin1", store.RoleAdmin)
	makeUser(t, srv, "op1", store.RoleOperator)
	cookie := loginAs(t, srv, adminID)

	req, _ := stdhttp.NewRequest("GET", ts.URL+"/api/users", nil)
	req.AddCookie(cookie)
	res, err := stdhttp.DefaultClient.Do(req)
	if err != nil {
		t.Fatalf("GET: %v", err)
	}
	defer res.Body.Close()
	if res.StatusCode != stdhttp.StatusOK {
		body, _ := io.ReadAll(res.Body)
		t.Fatalf("status: got %d body=%s", res.StatusCode, body)
	}
	var got listUsersResponse
	_ = json.NewDecoder(res.Body).Decode(&got)
	if len(got.Users) != 2 {
		t.Errorf("count: got %d want 2", len(got.Users))
	}
}
