package repository

import (
	"fmt"
	"hyapp-admin-server/internal/model"
	"strings"
)

func (s *Store) Search(keyword string, permissionCodes []string) ([]SearchResult, error) {
	return s.SearchWithAccess(keyword, permissionCodes, DataAccess{All: true})
}

func (s *Store) SearchWithAccess(keyword string, permissionCodes []string, access DataAccess) ([]SearchResult, error) {
	value := strings.TrimSpace(keyword)
	results := make([]SearchResult, 0, 12)
	if value == "" {
		value = "%"
	}
	like := "%" + strings.Trim(value, "%") + "%"
	permissions := permissionSet(permissionCodes)

	// 搜索是跨模块入口，结果必须先按权限裁剪，避免无菜单权限用户通过搜索发现业务数据。
	if _, ok := permissions["user:view"]; ok {
		var users []model.User
		query := s.db.Model(&model.User{}).Where("username LIKE ? OR name LIKE ? OR team LIKE ?", like, like, like)
		query = applyUserDataAccess(query, access)
		if err := query.Limit(4).Find(&users).Error; err != nil {
			return nil, err
		}
		for _, user := range users {
			results = append(results, SearchResult{
				Type:     "user",
				ID:       fmt.Sprintf("%d", user.ID),
				Title:    user.Name,
				Subtitle: fmt.Sprintf("%s / %s", user.Username, user.Team),
				Target:   "/system/users",
			})
		}
	}

	if _, ok := permissions["role:view"]; ok {
		var roles []model.Role
		if err := s.db.Where("name LIKE ? OR code LIKE ?", like, like).Limit(2).Find(&roles).Error; err != nil {
			return nil, err
		}
		for _, role := range roles {
			results = append(results, SearchResult{
				Type:     "role",
				ID:       fmt.Sprintf("%d", role.ID),
				Title:    role.Name,
				Subtitle: role.Code,
				Target:   "/system/roles",
			})
		}
	}

	return results, nil
}
