package http

import (
	stdhttp "net/http"
	"testing"
	"time"

	"github.com/oklog/ulid/v2"

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

// makeUser inserts a user with a known password ('test-password').
// Returns the user id. Used by RBAC middleware tests + the
// user-management handler tests.
//
//nolint:unused
func makeUser(t *testing.T, srv *Server, username string, role store.Role) string {
	t.Helper()
	id := ulid.Make().String()
	hash, err := auth.HashPassword("test-password")
	if err != nil {
		t.Fatalf("hash: %v", err)
	}
	if err := srv.deps.Store.CreateUser(t.Context(), store.User{
		ID: id, Username: username, PasswordHash: hash,
		Role: role, CreatedAt: time.Now().UTC(),
	}); err != nil {
		t.Fatalf("create user %s: %v", username, err)
	}
	return id
}

// loginAs gets a session cookie for the given user. Skips the real
// /api/auth/login handler for speed and to keep these helpers usable
// even when login validation is mid-flight elsewhere.
//
//nolint:unused
func loginAs(t *testing.T, srv *Server, userID string) *stdhttp.Cookie {
	t.Helper()
	rawToken, err := auth.NewToken()
	if err != nil {
		t.Fatalf("token: %v", err)
	}
	hash := auth.HashToken(rawToken)
	now := time.Now().UTC()
	if err := srv.deps.Store.CreateSession(t.Context(), store.Session{
		ID: hash, UserID: userID, CreatedAt: now,
		ExpiresAt: now.Add(8 * time.Hour),
	}, hash); err != nil {
		t.Fatalf("session: %v", err)
	}
	return &stdhttp.Cookie{
		Name:  sessionCookieName,
		Value: rawToken,
	}
}
