package logic

import (
	"context"
	"errors"
	"time"

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

	"github.com/shopspring/decimal"

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

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

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

// -----------------------wallets-----------------------
func (l *AddWalletsLogic) AddWallets(in *pb.AddWalletsReq) (*pb.AddWalletsResp, error) {
	updatedAt := time.Now()
	if in.UpdatedAt > 0 {
		updatedAt = time.Unix(in.UpdatedAt, 0)
	}

	balance, err := decimal.NewFromString(in.GetBalance())
	if err != nil {
		return nil, errors.New("invalid balance")
	}
	frozenBalance, err := decimal.NewFromString(in.GetFrozenBalance())
	if err != nil {
		return nil, errors.New("invalid frozenBalance")
	}

	tx, err := l.svcCtx.WalletModelsRW.Tx(l.ctx)
	if err != nil {
		return nil, err
	}

	_, err = tx.Wallet.Create().
		SetID(in.UserId).
		SetBalance(balance).
		SetFrozenBalance(frozenBalance).
		SetVersion(1).
		SetUpdatedAt(updatedAt).
		Save(l.ctx)
	if err != nil {
		_ = tx.Rollback()
		if models.IsConstraintError(err) {
			return &pb.AddWalletsResp{}, nil
		}
		return nil, err
	}

	if err = tx.Commit(); err != nil {
		return nil, err
	}

	return &pb.AddWalletsResp{}, nil
}
