<?php

declare(strict_types=1);

namespace PortalPeople\wordpressbridge;

use PortalPeople\wordpressbridge\services\WpService;
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 string $moduleId = 'ngauge-wordpress-bridge';
    public bool $enabled = true;
    public $controllerNamespace = 'PortalPeople\\wordpressbridge\\controllers';

    private ?WpService $wpService = null;

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

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

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

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

        if ($app instanceof WebApplication && $app->has('urlManager')) {
            $app->getUrlManager()->addRules([
                'POST v1/wp/sample'  => 'ngauge-wordpress-bridge/api/wp/sample',
                'POST v1/wp/create'  => 'ngauge-wordpress-bridge/api/wp/create',
            ], false);
        }
    }

    public function getWpService(): WpService
    {
        if ($this->wpService === null) {
            $this->wpService = new WpService();
        }

        return $this->wpService;
    }
}
