package cart

import (
	"context"
	"time"

	"bsm/full/module/ec/order/internal/models"
	pb "bsm/full/module/ec/order/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
	"git.apinb.com/bsm-sdk/core/service"
	"gorm.io/gorm"
)

// 修改购物车中的商品数量
func Modify(ctx context.Context, in *pb.CartSetRequest) (reply *pb.StatusReply, err error) {
	// parse authorization meta.
	_, err = service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}
	if len(in.GetUpdates()) > 0 {
		err = models.DBService.Transaction(func(tx *gorm.DB) error {
			for _, update := range in.Updates {
				err := tx.Table("order_cart").Where("id = ?", update.Id).Update("number", update.Number).Error
				if err != nil {
					printer.Error(err.Error())
					return err
				}
			}
			return nil
		})

	} else {
		if in.GetNumber() == 0 {
			return nil, errcode.ErrInvalidArgument
		}

		err = models.DBService.Table("order_cart").Where("id = ?", in.Id).Update("number", in.Number).Error
		if err != nil {
			printer.Error(err.Error())
			return nil, errcode.ErrDB
		}
	}

	return &pb.StatusReply{
		Code:    0,
		Message: "OK",
		Timeseq: time.Now().UnixNano(),
	}, nil

}
