<?php

declare(strict_types=1);

namespace PortalPeople\reports;

use Yii;
use PortalPeople\reports\services\ReportsService;
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\\reports\\controllers';
    public string $moduleId = 'ngauge-reports';

    // --- Configurable properties (override via params.php plugins key) ---
    public bool $enabled = true;

    private ?ReportsService $reportsService = null;

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

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

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

    public function getReportsService(): ReportsService
    {
        if ($this->reportsService === null) {
            $this->reportsService = new ReportsService();
        }

        return $this->reportsService;
    }

    public function bootstrap($app): void
    {
        $this->id = $this->moduleId;

        if (!isset($app->getModules()[$this->id])) {
            $app->setModule($this->id, $this);
        }

        if ($app instanceof WebApplication && $app->has('urlManager')) {
            $app->getUrlManager()->addRules([
                'POST v1/reports/validate'      => 'ngauge-reports/api/reports/validate',
                'POST v1/reports/report'        => 'ngauge-reports/api/reports/report',
                'POST v1/reports/bestsellers'   => 'ngauge-reports/api/reports/bestsellers',
                'POST v1/reports/turnoverbyday' => 'ngauge-reports/api/reports/turnoverbyday',
            ], false);
        }
    }
}
