<?php

declare(strict_types=1);

namespace PortalPeople\sitesetup;

use PortalPeople\sitesetup\services\SetupService;
use Yii;
use yii\base\BootstrapInterface;
use yii\web\Application as WebApplication;

/**
 * NGauge Site Setup Module
 *
 * Provides the one-time installation endpoint for a fresh NGauge instance.
 */
class Module extends \yii\base\Module implements BootstrapInterface
{
    /** @var string Unique module identifier used in params config */
    public string $moduleId = 'site-setup';

    /** @var bool Whether the module is active */
    public bool $enabled = true;

    private ?SetupService $setupService = null;

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

        $config = Yii::$app->params['plugins'][$this->moduleId] ?? [];

        $this->enabled = (bool)($config['enabled'] ?? $this->enabled);
    }

    public function bootstrap($app): void
    {
        $app->setModule($this->moduleId, $this);

        if (!($app instanceof WebApplication)) {
            return;
        }

        $app->getUrlManager()->addRules([
            'GET v1/site/setup/<email>' => 'site-setup/api/site/setup',
        ], false);
    }

    public function getSetupService(): SetupService
    {
        if ($this->setupService === null) {
            $this->setupService = new SetupService();
        }

        return $this->setupService;
    }
}
