package gamemanagement

import (
	"bytes"
	"context"
	"net/http"
	"net/http/httptest"
	"testing"

	"hyapp-admin-server/internal/integration/gameclient"
	"hyapp-admin-server/internal/integration/userclient"
	"hyapp-admin-server/internal/middleware"
	gamev1 "hyapp.local/api/proto/game/v1"

	"github.com/gin-gonic/gin"
)

type fakeRobotProfileSource struct {
	profiles  []RobotProfile
	requested int
}

func (s *fakeRobotProfileSource) RandomRobotProfiles(_ context.Context, count int) ([]RobotProfile, error) {
	s.requested = count
	return s.profiles[:count], nil
}

type fakeRobotUserClient struct {
	userclient.Client
	created []userclient.QuickCreateAccountRequest
}

func (c *fakeRobotUserClient) QuickCreateAccount(_ context.Context, req userclient.QuickCreateAccountRequest) (*userclient.QuickCreateAccountResult, error) {
	c.created = append(c.created, req)
	return &userclient.QuickCreateAccountResult{UserID: int64(9000 + len(c.created)), DisplayUserID: "robot"}, nil
}

func (c *fakeRobotUserClient) BatchGetUsers(_ context.Context, _ userclient.BatchGetUsersRequest) (map[int64]*userclient.User, error) {
	users := make(map[int64]*userclient.User, len(c.created))
	for index, created := range c.created {
		userID := int64(9001 + index)
		users[userID] = &userclient.User{UserID: userID, DisplayUserID: "robot", Username: created.Username, Avatar: created.Avatar}
	}
	return users, nil
}

type fakeRobotGameClient struct {
	gameclient.Client
	registered []int64
}

func (c *fakeRobotGameClient) RegisterDiceRobots(_ context.Context, req *gamev1.RegisterDiceRobotsRequest) (*gamev1.RegisterDiceRobotsResponse, error) {
	c.registered = append(c.registered, req.GetUserIds()...)
	robots := make([]*gamev1.DiceRobot, 0, len(req.GetUserIds()))
	for _, userID := range req.GetUserIds() {
		robots = append(robots, &gamev1.DiceRobot{AppCode: "lalu", GameId: "dice", UserId: userID, Status: "active"})
	}
	return &gamev1.RegisterDiceRobotsResponse{Robots: robots}, nil
}

func TestGenerateDiceRobotsUsesLikeiProfiles(t *testing.T) {
	gin.SetMode(gin.TestMode)
	profiles := &fakeRobotProfileSource{profiles: []RobotProfile{
		{Nickname: "likei-one", Avatar: "https://media.haiyihy.com/avatar/one.jpg"},
		{Nickname: "likei-two", Avatar: "https://media.haiyihy.com/avatar/two.jpg"},
	}}
	users := &fakeRobotUserClient{}
	games := &fakeRobotGameClient{}
	handler := New(games, users, nil, WithRobotProfileSource(profiles))

	recorder := httptest.NewRecorder()
	c, _ := gin.CreateTestContext(recorder)
	c.Set(middleware.ContextRequestID, "req-robot-test")
	c.Set(middleware.ContextUserID, uint(7))
	c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/admin/games/self/dice/robots:generate", bytes.NewBufferString(`{
		"count": 2,
		"nicknameLanguage": "ar",
		"avatarUrls": ["https://randomuser.me/api/portraits/men/1.jpg"],
		"country": "SA"
	}`))
	c.Request.Header.Set("Content-Type", "application/json")

	handler.GenerateDiceRobots(c)

	if recorder.Code != http.StatusOK {
		t.Fatalf("status = %d, body = %s", recorder.Code, recorder.Body.String())
	}
	if profiles.requested != 2 {
		t.Fatalf("profile source requested %d profiles, want 2", profiles.requested)
	}
	if len(users.created) != 2 {
		t.Fatalf("created users = %d, want 2", len(users.created))
	}
	if users.created[0].Username != "likei-one" || users.created[0].Avatar != "https://media.haiyihy.com/avatar/one.jpg" {
		t.Fatalf("first robot profile = %#v", users.created[0])
	}
	if users.created[1].Username != "likei-two" || users.created[1].Avatar != "https://media.haiyihy.com/avatar/two.jpg" {
		t.Fatalf("second robot profile = %#v", users.created[1])
	}
	if users.created[0].Language != "ar" || users.created[0].Source != "game_robot" || users.created[0].Country != "SA" {
		t.Fatalf("robot account metadata = %#v", users.created[0])
	}
	if len(games.registered) != 2 || games.registered[0] != 9001 || games.registered[1] != 9002 {
		t.Fatalf("registered user ids = %#v", games.registered)
	}
}
