package admin

import (
	"bytes"
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"testing"

	"bindbox-game/internal/pkg/core"
	"bindbox-game/internal/pkg/logger"
	"bindbox-game/internal/proposal"
	"bindbox-game/internal/repository/mysql"
	// dao/model not required in sqlite DDL
)

func Test_ListAppUsers_FilterByID(t *testing.T) {
	repo, err := mysql.NewSQLiteRepoForTest()
	if err != nil {
		t.Fatal(err)
	}
	if err := repo.GetDbW().Exec(`CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, nickname TEXT NOT NULL, avatar TEXT, mobile TEXT, openid TEXT, unionid TEXT, invite_code TEXT NOT NULL, inviter_id INTEGER, status INTEGER NOT NULL, douyin_id TEXT, created_at TEXT, updated_at TEXT, deleted_at TEXT)`).Error; err != nil {
		t.Fatal(err)
	}
	if err := repo.GetDbW().Exec(`INSERT INTO users (nickname,invite_code,status) VALUES ('u1','c1',1)`).Error; err != nil {
		t.Fatal(err)
	}
	if err := repo.GetDbW().Exec(`INSERT INTO users (nickname,invite_code,status) VALUES ('u2','c2',1)`).Error; err != nil {
		t.Fatal(err)
	}

	lg, err := logger.NewCustomLogger(nil, logger.WithOutputInConsole())
	if err != nil {
		t.Fatal(err)
	}
	mux, err := core.New(lg)
	if err != nil {
		t.Fatal(err)
	}

	dummyAuth := func(ctx core.Context) (proposal.SessionUserInfo, core.BusinessError) {
		return proposal.SessionUserInfo{Id: 1, IsSuper: 1}, nil
	}
	adminGroup := mux.Group("/api/admin", core.WrapAuthHandler(dummyAuth))
	adminGroup.GET("/users", New(lg, repo).ListAppUsers())

	// request with id filter = 1
	rr := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "/api/admin/users?id=1&page=1&page_size=20", bytes.NewBufferString(""))
	mux.ServeHTTP(rr, req)
	if rr.Code != http.StatusOK {
		t.Fatalf("code=%d body=%s", rr.Code, rr.Body.String())
	}
	var rsp map[string]interface{}
	if err := json.Unmarshal([]byte(rr.Body.String()), &rsp); err != nil {
		t.Fatal(err)
	}
	if int(rsp["total"].(float64)) != 1 {
		t.Fatalf("expect total=1 got %v", rsp["total"])
	}
}
