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 GetExchangeItemListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

// 商品列表（仅上架商品）
func (l *GetExchangeItemListLogic) GetExchangeItemList(in *plant.ExchangeItemListReq) (*plant.ExchangeItemListResp, error) {
	db := l.svcCtx.DB.Model(&plantModel.ExchangeItem{}).Where("status = 1")

	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.ExchangeItem
	if err := db.Limit(pageSize).Offset(offset).Order("created_at desc").Find(&list).Error; err != nil {
		return nil, err
	}

	var result []*plant.ExchangeItemInfo
	for _, item := range list {
		result = append(result, exchangeItemInfo(item))
	}
	return &plant.ExchangeItemListResp{List: result, Total: total}, nil
}
