package store

import (
	"testing"
)

func newTestStore(t *testing.T) *Store {
	t.Helper()
	s, err := New(":memory:")
	if err != nil {
		t.Fatalf("create test store: %v", err)
	}
	t.Cleanup(func() { s.Close() })
	return s
}

func TestCreateAndGetUser(t *testing.T) {
	s := newTestStore(t)

	u, err := s.CreateUser(User{
		Username: "admin", PasswordHash: "hash123", Role: "admin",
	})
	if err != nil {
		t.Fatalf("CreateUser: %v", err)
	}

	got, err := s.GetUserByUsername("admin")
	if err != nil {
		t.Fatalf("GetUserByUsername: %v", err)
	}
	if got.ID != u.ID {
		t.Fatal("user ID mismatch")
	}
	if got.Role != "admin" {
		t.Fatalf("role mismatch: %q", got.Role)
	}
}

func TestUserCount(t *testing.T) {
	s := newTestStore(t)

	count, err := s.UserCount()
	if err != nil {
		t.Fatalf("UserCount: %v", err)
	}
	if count != 0 {
		t.Fatalf("expected 0 users, got %d", count)
	}

	s.CreateUser(User{Username: "u1", PasswordHash: "h", Role: "viewer"})
	count, _ = s.UserCount()
	if count != 1 {
		t.Fatalf("expected 1 user, got %d", count)
	}
}

func TestDeleteUser(t *testing.T) {
	s := newTestStore(t)

	u, _ := s.CreateUser(User{Username: "del-me", PasswordHash: "h", Role: "viewer"})
	err := s.DeleteUser(u.ID)
	if err != nil {
		t.Fatalf("DeleteUser: %v", err)
	}

	_, err = s.GetUserByID(u.ID)
	if err == nil {
		t.Fatal("expected error getting deleted user")
	}
}

func TestUpdateUser(t *testing.T) {
	s := newTestStore(t)

	u, _ := s.CreateUser(User{Username: "orig", PasswordHash: "h", Role: "viewer"})
	u.Username = "renamed"
	u.Role = "admin"

	err := s.UpdateUser(u)
	if err != nil {
		t.Fatalf("UpdateUser: %v", err)
	}

	got, _ := s.GetUserByID(u.ID)
	if got.Username != "renamed" {
		t.Fatalf("expected username 'renamed', got %q", got.Username)
	}
	if got.Role != "admin" {
		t.Fatalf("expected role 'admin', got %q", got.Role)
	}
}

