// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2

package wallet

import (
	"context"
	"strconv"
	"time"

	"juwan-backend/app/wallet/rpc/pb"
	"juwan-backend/common/utils/contextj"

	"juwan-backend/app/wallet/api/internal/svc"
	"juwan-backend/app/wallet/api/internal/types"

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

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

// 获取流水
func NewListTransactionsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListTransactionsLogic {
	return &ListTransactionsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListTransactionsLogic) ListTransactions(req *types.PageReq) (resp *types.TransactionListResp, err error) {
	userID, err := contextj.UserIDFrom(l.ctx)
	if err != nil {
		return nil, err
	}

	if req.Limit <= 0 {
		req.Limit = 20
	}

	out, err := l.svcCtx.WalletRpc.SearchWalletTransactions(l.ctx, &pb.SearchWalletTransactionsReq{
		Offset: req.Offset,
		Limit:  req.Limit,
		UserId: &userID,
	})
	if err != nil {
		return nil, err
	}

	items := make([]types.Transaction, 0, len(out.GetWalletTransactions()))
	for _, item := range out.GetWalletTransactions() {
		if item == nil {
			continue
		}
		tx := types.Transaction{
			Id:          item.Id,
			Type:        item.Type,
			Amount:      item.Amount,
			Description: item.Description,
			CreatedAt:   time.Unix(item.CreatedAt, 0).Format(time.RFC3339),
		}
		if item.OrderId > 0 {
			tx.OrderId = strconv.FormatInt(item.OrderId, 10)
		}
		items = append(items, tx)
	}

	return &types.TransactionListResp{
		Items: items,
		Meta: types.PageMeta{
			Total:  int64(len(items)),
			Offset: req.Offset,
			Limit:  req.Limit,
		},
	}, nil
}
