package tests

import (
	"testing"
)

// PublicUserInfo 公开用户信息响应
type PublicUserInfo struct {
	ID       string `json:"id"`
	Username string `json:"username"`
	Nickname string `json:"nickname"`
	Avatar   string `json:"avatar"`
}

// SearchUsersResp 搜索用户响应
type SearchUsersResp struct {
	Items []PublicUserInfo `json:"items"`
	Total int64           `json:"total"`
}

func TestSearchUsers(t *testing.T) {
	// Ensure base users are created (Admin, User1, User2)
	ensureUsers(t)

	// Test 1: Search users without auth (should fail)
	t.Run("Search Users Without Auth", func(t *testing.T) {
		resp := doRequest(t, "GET", "/api/auth/users", nil, "")
		// Should return 401 unauthorized
		assertStatus(t, resp, 401)
	})

	// Test 2: Search users with auth
	t.Run("Search Users With Auth", func(t *testing.T) {
		resp := doRequest(t, "GET", "/api/auth/users", nil, User1Token)
		assertStatus(t, resp, 200)

		var data SearchUsersResp
		decodeResponse(t, resp, &data)
		t.Logf("Search users response: total=%d, items=%d", data.Total, len(data.Items))

		// Should return users
		if data.Total <= 0 {
			t.Errorf("Expected some users, got total=%d", data.Total)
		}
	})

	// Test 3: Search users with keyword
	t.Run("Search Users With Keyword", func(t *testing.T) {
		resp := doRequest(t, "GET", "/api/auth/users?keyword=user1", nil, User1Token)
		assertStatus(t, resp, 200)

		var data SearchUsersResp
		decodeResponse(t, resp, &data)
		t.Logf("Search users with keyword: total=%d, items=%d", data.Total, len(data.Items))
	})

	// Test 4: Verify public info is returned (only id, username, nickname, avatar)
	t.Run("Verify Public Info Only", func(t *testing.T) {
		resp := doRequest(t, "GET", "/api/auth/users?limit=1", nil, User1Token)
		assertStatus(t, resp, 200)

		var data SearchUsersResp
		decodeResponse(t, resp, &data)

		if len(data.Items) > 0 {
			user := data.Items[0]
			// Should have these fields
			if user.ID == "" {
				t.Error("Expected id to be present")
			}
			if user.Username == "" {
				t.Error("Expected username to be present")
			}
			// Nickname and avatar can be empty but field should exist
			t.Logf("User public info: id=%s, username=%s, nickname=%s, avatar=%s",
				user.ID, user.Username, user.Nickname, user.Avatar)
		}
	})

	// Test 5: Admin can search users too
	t.Run("Admin Can Search Users", func(t *testing.T) {
		resp := doRequest(t, "GET", "/api/auth/users", nil, AdminToken)
		assertStatus(t, resp, 200)

		var data SearchUsersResp
		decodeResponse(t, resp, &data)
		t.Logf("Admin search users: total=%d", data.Total)
	})
}
