<?php

declare(strict_types=1);

namespace portalpeople\apidocs;

use portalpeople\apidocs\services\DocumentationService;
use Yii;
use yii\base\BootstrapInterface;
use yii\base\Module as BaseModule;
use yii\web\Application as WebApplication;

class Module extends BaseModule implements BootstrapInterface
{
    public $controllerNamespace = 'portalpeople\\apidocs\\controllers';

    /** @var array<int, string> */
    public array $swaggerScanDirs = [];

    public string $apiKey = '';

    private ?DocumentationService $documentationService = null;

    public function init(): void
    {
        parent::init();

        /** @var array<string, mixed> $config */
        $config = Yii::$app->params['plugins']['api-docs'] ?? [];

        if (isset($config['apiKey'])) {
            $this->apiKey = (string) $config['apiKey'];
        }

        if (isset($config['swaggerScanDirs']) && is_array($config['swaggerScanDirs'])) {
            $this->swaggerScanDirs = $config['swaggerScanDirs'];
        }

        if ($this->swaggerScanDirs === []) {
            $this->swaggerScanDirs = [
                Yii::getAlias('@vendor/portalpeople/ngauge-api-docs/src/swagger/SwaggerDefinitions.php'),
                Yii::getAlias('@backend/models/Cartlinessearch.php'),
                Yii::getAlias('@backend/models/Cartsbesearch.php'),
            ];
        }
    }

    public function bootstrap($app): void
    {
        if (!isset($app->getModules()['api-docs'])) {
            $app->setModule('api-docs', [
                'class' => self::class,
            ]);
        }

        if ($app instanceof WebApplication && $app->has('urlManager')) {
            $app->getUrlManager()->addRules([
                'GET v1/documentation' => 'api-docs/api/documentation/index',
                'GET v1/documentation/docapi' => 'api-docs/api/documentation/docapi',
                'GET v1/documentation/page' => 'api-docs/api/documentation/page',
                'GET v1/documentation/page/<url:.+>' => 'api-docs/api/documentation/page',
            ], false);
        }
    }

    public function getDocumentationService(): DocumentationService
    {
        if ($this->documentationService === null) {
            $this->documentationService = new DocumentationService();
        }

        return $this->documentationService;
    }
}
