<?php

declare(strict_types=1);

namespace portalpeople\orders\controllers\api;

use frontend\models\Cart;
use portalpeople\orders\Module;
use Yii;
use yii\rest\Controller;

/**
 * @OA\Tag(
 *     name="Orders",
 *     description="Order creation and management"
 * )
 */
class OrderController extends Controller
{
    /**
     * @OA\Post(
     *     path="/v1/order/new",
     *     tags={"Orders"},
     *     summary="Create a new order from API payload",
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(type="object")
     *     ),
     *     @OA\Response(response=200, description="Cart model created"),
     *     @OA\Response(response=503, description="Module unavailable")
     * )
     */
    public function actionNew(): Cart
    {
        /** @var Module|null $module */
        $module = Yii::$app->getModule('ngauge-orders');

        if ($module === null || !method_exists($module, 'getOrderService')) {
            Yii::error('ngauge-orders module unavailable in OrderController::actionNew', __CLASS__);
            Yii::$app->response->statusCode = 503;
            return new Cart();
        }

        return $module->getOrderService()->createFromApi(Yii::$app->request->post() ?? []);
    }
}
