<?php

declare(strict_types=1);

namespace portalpeople\products\controllers\api;

use portalpeople\products\Module;
use Yii;
use yii\rest\Controller;
use yii\web\Response;

/**
 * @OA\Tag(
 *     name="Products",
 *     description="Product catalogue and centre product listings"
 * )
 */
class ProductsController extends Controller
{
    /**
     * @OA\Get(
     *     path="/v1/products/centerproducts",
     *     tags={"Products"},
     *     summary="List all active products",
     *     @OA\Response(
     *         response=200,
     *         description="Array of active products",
     *         @OA\JsonContent(type="array", @OA\Items(type="object"))
     *     ),
     *     @OA\Response(response=503, description="Module unavailable")
     * )
     */
    public function actionCenterproducts(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        Yii::$app->response->statusCode = 200;

        /** @var Module|null $module */
        $module = Yii::$app->getModule('ngauge-products');

        if ($module === null || !method_exists($module, 'getProductsService')) {
            Yii::error('ngauge-products module unavailable in ProductsController::actionCenterproducts', __CLASS__);
            Yii::$app->response->statusCode = 503;
            return [];
        }

        return $module->getProductsService()->getCenterProducts();
    }
}
