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

package order

import (
	"context"
	"errors"
	"time"

	"juwan-backend/app/order/rpc/orderservice"

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

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

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

// 再来一单
func NewReorderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ReorderLogic {
	return &ReorderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ReorderLogic) Reorder(req *types.PathId) (resp *types.CreateOrderResp, err error) {
	oldOrderResp, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	oldOrder := oldOrderResp.GetOrders()
	if oldOrder == nil {
		return nil, errors.New("order not found")
	}

	now := time.Now().Unix()
	status := "pending_payment"
	searchText := oldOrder.GetSearchText()

	addReq := &orderservice.AddOrdersReq{
		ConsumerId:      oldOrder.GetConsumerId(),
		PlayerId:        oldOrder.GetPlayerId(),
		ServiceSnapshot: oldOrder.GetServiceSnapshot(),
		Status:          &status,
		TotalPrice:      oldOrder.GetTotalPrice(),
		SearchText:      &searchText,
		CreatedAt:       &now,
		UpdatedAt:       &now,
	}
	if oldOrder.ShopId != nil {
		addReq.ShopId = oldOrder.ShopId
	}
	if oldOrder.Note != nil {
		addReq.Note = oldOrder.Note
	}

	addResp, err := l.svcCtx.OrderRpc.AddOrders(l.ctx, addReq)
	if err != nil {
		return nil, err
	}

	created, err := l.svcCtx.OrderRpc.GetOrdersById(l.ctx, &orderservice.GetOrdersByIdReq{Id: addResp.Id})
	if err != nil {
		return nil, err
	}

	return &types.CreateOrderResp{Ok: true, Order: toAPIOrder(created.GetOrders())}, nil
}
