<?php

declare(strict_types=1);

namespace PortalPeople\monitor;

use Yii;
use yii\base\BootstrapInterface;
use yii\base\Module as BaseModule;
use yii\web\Application as WebApplication;

/**
 * NGauge Monitor Module
 *
 * Provides health monitoring surfaces for API and backend web:
 *
 *   API (NGaugeApi app):
 *     GET v1/monitor/all
 *     GET v1/monitor/health
 *     GET v1/monitor/queues
 *     GET v1/monitor/db
 *     GET v1/monitor/disk
 *     GET v1/monitor/errors
 *     GET v1/monitor/wrappers
 *
 *   Web (ngauge_commerce backend app):
 *     GET monitor          → dashboard index
 *     GET monitor/all      → JSON (AJAX polling)
 *     GET monitor/health   → JSON
 *     GET monitor/queues   → JSON
 *     GET monitor/db       → JSON
 *     GET monitor/disk     → JSON
 *     GET monitor/errors   → JSON
 *
 * Install:
 *   composer require portalpeople/ngauge-monitor
 *
 * Console commands remain in NGauge_Base/console/controllers/MonitorController.php
 * and consume the module-local monitor service.
 */
class Module extends BaseModule implements BootstrapInterface
{
    public string $moduleId = 'ngauge-monitor';
    public bool $enabled = true;

    /** @var string PSR-4 root for sub-namespace controller resolution */
    public $controllerNamespace = 'PortalPeople\\monitor\\controllers';

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

        $config = Yii::$app->params['plugins']['ngauge-monitor'] ?? [];

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

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

        if (!($app instanceof WebApplication) || !$app->has('urlManager')) {
            return;
        }

        if ($app->id === 'NGaugeApi') {
            // REST JSON endpoints – consumed by monitoring systems / scripts
            $app->getUrlManager()->addRules([
                'GET v1/monitor/all'      => 'ngauge-monitor/api/monitor/all',
                'GET v1/monitor/health'   => 'ngauge-monitor/api/monitor/health',
                'GET v1/monitor/queues'   => 'ngauge-monitor/api/monitor/queues',
                'GET v1/monitor/db'       => 'ngauge-monitor/api/monitor/db',
                'GET v1/monitor/disk'     => 'ngauge-monitor/api/monitor/disk',
                'GET v1/monitor/errors'   => 'ngauge-monitor/api/monitor/errors',
                'GET v1/monitor/wrappers' => 'ngauge-monitor/api/monitor/wrappers',
            ], false);
        } else {
            // Backend HTML dashboard + AJAX JSON endpoints
            $app->getUrlManager()->addRules([
                'monitor'                  => 'ngauge-monitor/web/monitor/index',
                'monitor/<action:[\w-]+>'  => 'ngauge-monitor/web/monitor/<action>',
            ], false);
        }
    }
}
