package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	sysModel "sundynix-micro-go/app/system/model"
	"sundynix-micro-go/app/system/rpc/internal/svc"
	"sundynix-micro-go/app/system/rpc/system"
)

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

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

func (l *GetClientListLogic) GetClientList(in *system.ClientListReq) (*system.ClientListResp, error) {
	var list []sysModel.SundynixClient
	var total int64
	db := l.svcCtx.DB.Model(&sysModel.SundynixClient{})
	if in.Name != "" {
		db = db.Where("name LIKE ?", "%"+in.Name+"%")
	}
	db.Count(&total)
	current, pageSize := int(in.Current), int(in.PageSize)
	if current <= 0 {
		current = 1
	}
	if pageSize <= 0 {
		pageSize = 10
	}
	if err := db.Offset((current - 1) * pageSize).Limit(pageSize).Order("created_at DESC").Find(&list).Error; err != nil {
		return nil, fmt.Errorf("查询客户端列表失败")
	}
	var items []*system.ClientInfo
	for _, c := range list {
		items = append(items, &system.ClientInfo{
			Id: c.ID, ClientId: c.ClientID, Name: c.Name, GrantType: c.GrantType,
			AdditionalInfo: c.AdditionalInfo, ActiveTimeout: int64(c.ActiveTimeout),
		})
	}
	return &system.ClientListResp{List: items, Total: total}, nil
}
