package logic

import (
	"context"

	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"

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

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

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

// 配置 - 徽章配置列表
func (l *GetBadgeConfigListLogic) GetBadgeConfigList(in *plant.BadgeConfigListReq) (*plant.BadgeConfigListResp, error) {
	db := l.svcCtx.DB.Model(&plantModel.BadgeConfig{})
	if in.Dimension != "" {
		db = db.Where("dimension = ?", in.Dimension)
	}

	var total int64
	db.Count(&total)

	pageSize := int(in.PageSize)
	if pageSize <= 0 {
		pageSize = 20
	}
	offset := (int(in.Current) - 1) * pageSize
	if offset < 0 {
		offset = 0
	}

	var list []plantModel.BadgeConfig
	if err := db.Order("dimension asc, group_id asc, tier asc").
		Limit(pageSize).Offset(offset).Find(&list).Error; err != nil {
		return nil, err
	}

	var result []*plant.BadgeConfigInfo
	for _, item := range list {
		result = append(result, &plant.BadgeConfigInfo{
			Id:             item.ID,
			Name:           item.Name,
			Description:    item.Description,
			Dimension:      item.Dimension,
			GroupId:        item.GroupID,
			Tier:           int32(item.Tier),
			TargetAction:   item.TargetAction,
			Threshold:      item.Threshold,
			RewardSunlight: item.RewardSunlight,
		})
	}

	return &plant.BadgeConfigListResp{List: result, Total: total}, nil
}
