package user

import (
	"context"
	"strconv"
	"strings"
	"time"

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

// BusinessUserLookup 只返回同 app_code 的 active 用户，并按查询类型收敛匹配范围。
// 数字 keyword 只做短号和 user_id 精确匹配；昵称搜索要求调用方已校验最小长度。
func (r *Repository) BusinessUserLookup(ctx context.Context, keyword string, numericKeyword bool, pageSize int32) ([]userdomain.BusinessUserLookupItem, error) {
	if r == nil || r.db == nil {
		return nil, xerr.New(xerr.Unavailable, "mysql repository is not configured")
	}
	app := appcode.FromContext(ctx)
	limit := int(pageSize)
	if limit <= 0 {
		limit = 20
	}

	var args []any
	query := `SELECT ` + userSelectColumns + ` FROM users WHERE app_code = ? AND status = ?`
	args = append(args, app, string(userdomain.StatusActive))
	if numericKeyword {
		userID := int64(0)
		if parsed, err := strconv.ParseInt(keyword, 10, 64); err == nil {
			userID = parsed
		}
		nowMs := time.Now().UnixMilli()
		// 业务查人入口服务运营搜索，必须同时接受默认短号、当前快照号和 user_display_user_ids 的 active 事实号；
		// 靓号发放或过期恢复过程中 users.current_display_user_id 可能短暂落后，事实表命中后列表仍返回当前用户投影。
		query += ` AND (
				current_display_user_id = ?
				OR default_display_user_id = ?
				OR user_id = ?
				OR EXISTS (
					SELECT 1
					FROM user_display_user_ids du
					WHERE du.app_code = users.app_code
					  AND du.user_id = users.user_id
					  AND du.display_user_id = ?
					  AND du.status = ?
					  AND (du.expires_at_ms IS NULL OR du.expires_at_ms = 0 OR du.expires_at_ms > ?)
					LIMIT 1
				)
			)
			ORDER BY CASE
				WHEN current_display_user_id = ? THEN 0
				WHEN default_display_user_id = ? THEN 1
				WHEN user_id = ? THEN 2
				ELSE 3
			END, updated_at_ms DESC, user_id DESC
			LIMIT ?`
		args = append(args,
			keyword,
			keyword,
			userID,
			keyword,
			string(userdomain.DisplayUserIDStatusActive),
			nowMs,
			keyword,
			keyword,
			userID,
			limit,
		)
	} else {
		query += ` AND username LIKE ? ESCAPE '\\'
			ORDER BY updated_at_ms DESC, user_id DESC
			LIMIT ?`
		args = append(args, "%"+escapeLikeKeyword(keyword)+"%", limit)
	}

	rows, err := r.db.QueryContext(ctx, query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	items := make([]userdomain.BusinessUserLookupItem, 0, limit)
	for rows.Next() {
		user, err := ScanUser(rows)
		if err != nil {
			return nil, err
		}
		items = append(items, businessUserLookupItem(user))
	}
	return items, rows.Err()
}

func businessUserLookupItem(user userdomain.User) userdomain.BusinessUserLookupItem {
	return userdomain.BusinessUserLookupItem{
		UserID:        user.UserID,
		DisplayUserID: user.CurrentDisplayUserID,
		Username:      user.Username,
		Avatar:        user.Avatar,
		Status:        user.Status,
		RegionID:      user.RegionID,
		RegionCode:    user.RegionCode,
		RegionName:    user.RegionName,
	}
}

func escapeLikeKeyword(value string) string {
	value = strings.ReplaceAll(value, `\`, `\\`)
	value = strings.ReplaceAll(value, `%`, `\%`)
	value = strings.ReplaceAll(value, `_`, `\_`)
	return value
}
