package logic

import (
	"context"
	"juwan-backend/app/wallet/rpc/internal/models"
	"juwan-backend/app/wallet/rpc/internal/models/wallet"
	"juwan-backend/app/wallet/rpc/internal/svc"
	"juwan-backend/app/wallet/rpc/pb"

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

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

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

func (l *GetWalletsByIdLogic) GetWalletsById(in *pb.GetWalletsByIdReq) (*pb.GetWalletsByIdResp, error) {
	item, err := l.svcCtx.WalletModelsRO.Wallet.Query().
		Where(wallet.IDEQ(in.Id)).
		First(l.ctx)
	if err != nil {
		if models.IsNotFound(err) {
			if _, e := l.svcCtx.WalletModelsRO.Wallet.Create().SetID(in.Id).Save(l.ctx); e != nil {
				return nil, e
			}
			return &pb.GetWalletsByIdResp{}, nil
		}
		return nil, err
	}

	updatedAt := int64(0)
	if !item.UpdatedAt.IsZero() {
		updatedAt = item.UpdatedAt.Unix()
	}

	return &pb.GetWalletsByIdResp{
		Wallets: &pb.Wallets{
			UserId:        item.ID,
			Balance:       item.Balance.String(),
			FrozenBalance: item.FrozenBalance.String(),
			UpdatedAt:     updatedAt,
			Version:       int64(item.Version),
		},
	}, nil
}
