<?php

declare(strict_types=1);

namespace PortalPeople\dataexchange;

use PortalPeople\dataexchange\services\DataExchangeService;
use yii\base\BootstrapInterface;
use yii\base\Module as BaseModule;
use Yii;

/**
 * ngauge-data-exchange module
 *
 * ERP data import/export: order downloads, CSV exports, model sync, Sage integration.
 */
class Module extends BaseModule implements BootstrapInterface
{
    public string $moduleId  = 'ngauge-data-exchange';
    public bool   $enabled   = true;

    /** @var DataExchangeService|null */
    private ?DataExchangeService $dataExchangeService = null;

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

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

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

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

        if ($app instanceof \yii\web\Application) {
            $app->getUrlManager()->addRules([
                'GET v1/data/index'              => 'ngauge-data-exchange/api/data/index',
                'GET v1/data/model'              => 'ngauge-data-exchange/api/data/model',
                'POST v1/data/upload'            => 'ngauge-data-exchange/api/data/upload',
                'GET v1/data/downloadorders'     => 'ngauge-data-exchange/api/data/downloadorders',
                'GET v1/data/downloadpaidorders' => 'ngauge-data-exchange/api/data/downloadpaidorders',
                'GET v1/data/downloadcsv'        => 'ngauge-data-exchange/api/data/downloadcsv',
                'GET v1/data/downloadpaidcsv'    => 'ngauge-data-exchange/api/data/downloadpaidcsv',
                'GET v1/data/downloadcsvgroup'   => 'ngauge-data-exchange/api/data/downloadcsvgroup',
                'POST v1/data/downloaded'        => 'ngauge-data-exchange/api/data/downloaded',
                'GET v1/data/download'           => 'ngauge-data-exchange/api/data/download',
                'GET v1/data/check'              => 'ngauge-data-exchange/api/data/check',
                'OPTIONS v1/data/check'          => 'ngauge-data-exchange/api/data/check',
                'POST v1/data/checkids'          => 'ngauge-data-exchange/api/data/checkids',
                'POST v1/data/sagedata'          => 'ngauge-data-exchange/api/data/sagedata',
            ], false);
        }
    }

    public function getDataExchangeService(): DataExchangeService
    {
        if ($this->dataExchangeService === null) {
            $this->dataExchangeService = new DataExchangeService();
        }

        return $this->dataExchangeService;
    }
}
