package logic

import (
	"context"

	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetUserListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetUserListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserListLogic {
	return &GetUserListLogic{ctx: ctx, svcCtx: svcCtx, Logger: logx.WithContext(ctx)}
}

func (l *GetUserListLogic) GetUserList(in *system.GetUserListReq) (*system.GetUserListResp, error) {
	db := l.svcCtx.DB.Model(&sysModel.SundynixUser{})
	if in.Name != "" {
		db = db.Where("name LIKE ?", "%"+in.Name+"%")
	}
	if in.Account != "" {
		db = db.Where("account LIKE ?", "%"+in.Account+"%")
	}

	var total int64
	db.Count(&total)

	var list []sysModel.SundynixUser
	pageSize := int(in.PageSize)
	if pageSize <= 0 {
		pageSize = 10
	}
	current := int(in.Current)
	if current <= 0 {
		current = 1
	}
	db.Preload("Roles").Offset((current - 1) * pageSize).Limit(pageSize).Order("created_at DESC").Find(&list)

	var protoList []*system.UserInfo
	for _, u := range list {
		protoList = append(protoList, convertUserToProto(&u))
	}
	return &system.GetUserListResp{List: protoList, Total: total}, nil
}
