<?php

declare(strict_types=1);

namespace PortalPeople\apidocs\controllers\api;

use OpenApi\Annotations as OA;
use PortalPeople\apidocs\Module as ApiDocsModule;
use Yii;
use yii\rest\Controller;
use yii\web\NotFoundHttpException;
use yii\web\Response;

/**
 * @OA\Tag(
 *   name="API Documentation",
 *   description="Swagger/OpenAPI documentation and page endpoints"
 * )
 */
class DocumentationController extends Controller
{
    public function beforeAction($action): bool
    {
        if (Yii::$app->user->isGuest) {
            $this->redirect(['/admin/user/login', 'redirect' => Yii::$app->request->url]);
            return false;
        }

        return parent::beforeAction($action);
    }

    public function actions(): array
    {
        /** @var ApiDocsModule|null $module */
        $module = Yii::$app->getModule('api-docs');

        if ($module instanceof ApiDocsModule) {
            return $module->getDocumentationService()->buildSwaggerActionsConfig($module->swaggerScanDirs, $module->apiKey);
        }

        return [];
    }

    /**
     * @OA\Get(
     *   path="/v1/documentation/page",
     *   tags={"API Documentation"},
     *   summary="Render documentation page by URL slug",
     *   @OA\Parameter(name="url", in="query", required=true, @OA\Schema(type="string")),
     *   @OA\Response(response=200, description="HTML page")
     * )
     */
    public function actionPage(string $url)
    {
        Yii::$app->response->format = Response::FORMAT_HTML;
        $this->layout = '@backend/views/layouts/pdf';

        /** @var ApiDocsModule|null $module */
        $module = Yii::$app->getModule('api-docs');
        $model = $module instanceof ApiDocsModule
            ? $module->getDocumentationService()->findPageByUrl($url)
            : null;

        if ($model === null) {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

        return $this->render('page', ['model' => $model]);
    }
}
