package repository

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

// ListMoneyScopeOperators 返回所有配置过财务/数据范围的后台用户及其范围；
// 社交 BI 的"运营人员"就是这批人，不再依赖固定 team_id 约定。
func (s *Store) ListMoneyScopeOperators() ([]model.User, map[uint][]model.UserMoneyScope, error) {
	var scopes []model.UserMoneyScope
	if err := s.db.Order("user_id ASC, app_code ASC, region_id ASC").Find(&scopes).Error; err != nil {
		return nil, nil, err
	}
	scopesByUser := map[uint][]model.UserMoneyScope{}
	userIDs := make([]uint, 0, len(scopes))
	for _, scope := range scopes {
		if _, ok := scopesByUser[scope.UserID]; !ok {
			userIDs = append(userIDs, scope.UserID)
		}
		scopesByUser[scope.UserID] = append(scopesByUser[scope.UserID], scope)
	}
	if len(userIDs) == 0 {
		return []model.User{}, scopesByUser, nil
	}
	var users []model.User
	if err := s.db.Where("id IN ?", userIDs).Order("id ASC").Find(&users).Error; err != nil {
		return nil, nil, err
	}
	return users, scopesByUser, nil
}
