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

package order

import (
	"context"

	"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 CreateAndPayOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// 创建并支付订单
func NewCreateAndPayOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateAndPayOrderLogic {
	return &CreateAndPayOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateAndPayOrderLogic) CreateAndPayOrder(req *types.CreateOrderReq) (resp *types.CreateOrderResp, err error) {
	created, err := NewCreateOrderLogic(l.ctx, l.svcCtx).CreateOrder(req)
	if err != nil {
		return nil, err
	}

	if err = transitionOrderStatus(l.ctx, l.svcCtx, created.Order.Id, "pending_accept", false, false, false, false); err != nil {
		return nil, err
	}

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

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