package user

import (
	"github.com/linmadan/egglib-go/core/application"
	"github.com/linmadan/egglib-go/utils/tool_funs"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/user/query"
	"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
)

type UserService struct{}

func (service *UserService) ListUsers(listUserQuery *query.ListUserQuery) (interface{}, error) {
	transactionContext, err := factory.CreateTransactionContext(nil)
	if err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	if err := transactionContext.StartTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	defer func() {
		_ = transactionContext.RollbackTransaction()
	}()
	userRepo := factory.CreateUserRepository(map[string]interface{}{
		"transactionContext": transactionContext,
	})
	count, list, err := userRepo.Find(map[string]interface{}{
		"companyId": listUserQuery.CompanyId,
		"name":      listUserQuery.Name,
		"status":    domain.UserStatusEnable,
	})
	if err != nil {
		return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
	}
	if err := transactionContext.CommitTransaction(); err != nil {
		return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
	}
	return tool_funs.SimpleWrapGridMap(int64(count), list), nil
}