<?php

namespace PortalPeople\cart\controllers\api;

use Yii;
use yii\rest\Controller;
use yii\web\BadRequestHttpException;
use yii\web\ServerErrorHttpException;
use PortalPeople\cart\models\Cart;

/**
 * Order REST API Controller
 *
 * Provides endpoints for creating carts/orders via API.
 *
 * Routes:
 *   POST  /api/cart/order/create   Create a cart from EDI/API payload
 */
class OrderController extends Controller
{
    public function behaviors(): array
    {
        $behaviors = parent::behaviors();

        $behaviors['contentNegotiator']['formats'] = [
            'application/json' => \yii\web\Response::FORMAT_JSON,
        ];

        return $behaviors;
    }

    /**
     * Create one or more carts from an EDI/API order payload.
     *
     * Accepts JSON body matching the fromApi() contract:
     * single order object or array of order objects.
     *
     * @return array
     * @throws BadRequestHttpException
     * @throws ServerErrorHttpException
     */
    public function actionCreate(): array
    {
        $body = Yii::$app->request->bodyParams;

        if (empty($body)) {
            throw new BadRequestHttpException('Request body is empty or not valid JSON.');
        }

        $result = Cart::fromApi($body);

        if (isset($result['errors'])) {
            Yii::$app->response->statusCode = $result['code'] ?? 422;
        }

        return $result;
    }
}
