package user

import (
	"context"
	"strings"
	"unicode/utf8"

	"hyapp/pkg/xerr"
	userdomain "hyapp/services/user-service/internal/domain/user"
)

const (
	BusinessSceneManagerResourceGrant = "manager_resource_grant"
	BusinessSceneManagerVIPGrant      = "manager_vip_grant"
	BusinessSceneManagerUpdateLevel   = "manager_update_user_level"
	BusinessSceneManagerAddBDLeader   = "manager_add_bd_leader"
	BusinessSceneManagerAddAdmin      = "manager_add_admin"
	BusinessSceneManagerAddSuperadmin = "manager_add_superadmin"
	BusinessSceneManagerBlockUser     = "manager_block_user"
	BusinessSceneManagerTransfer      = "manager_transfer_user_country"

	defaultBusinessLookupPageSize = 20
	maxBusinessLookupPageSize     = 20
)

// BusinessUserLookup 执行业务场景用户查询。调用方必须先完成该 scene 的能力校验；
// service 层仍校验 scene 和 keyword，避免未来入口把它误用成全局用户搜索。
func (s *Service) BusinessUserLookup(ctx context.Context, scene string, keyword string, pageSize int32) ([]userdomain.BusinessUserLookupItem, error) {
	scene = strings.ToLower(strings.TrimSpace(scene))
	if !isBusinessUserLookupScene(scene) {
		return nil, xerr.New(xerr.InvalidArgument, "business lookup scene is invalid")
	}
	if s.userRepository == nil {
		return nil, xerr.New(xerr.Unavailable, "user repository is not configured")
	}
	keyword = strings.TrimSpace(keyword)
	numericKeyword := isASCIIInteger(keyword)
	if keyword == "" || (!numericKeyword && utf8.RuneCountInString(keyword) < 2) {
		return nil, xerr.New(xerr.InvalidArgument, "keyword is invalid")
	}
	if pageSize <= 0 {
		pageSize = defaultBusinessLookupPageSize
	}
	if pageSize > maxBusinessLookupPageSize {
		pageSize = maxBusinessLookupPageSize
	}
	return s.userRepository.BusinessUserLookup(ctx, keyword, numericKeyword, pageSize)
}

func isBusinessUserLookupScene(scene string) bool {
	switch scene {
	case BusinessSceneManagerResourceGrant,
		BusinessSceneManagerVIPGrant,
		BusinessSceneManagerUpdateLevel,
		BusinessSceneManagerAddBDLeader,
		BusinessSceneManagerAddAdmin,
		BusinessSceneManagerAddSuperadmin,
		BusinessSceneManagerBlockUser,
		BusinessSceneManagerTransfer:
		return true
	default:
		return false
	}
}

func isASCIIInteger(value string) bool {
	if value == "" {
		return false
	}
	for _, ch := range value {
		if ch < '0' || ch > '9' {
			return false
		}
	}
	return true
}
