<?php

namespace PortalPeople\stripe;

use Yii;
use yii\base\BootstrapInterface;
use yii\base\Module as BaseModule;

class Module extends BaseModule implements BootstrapInterface
{
    public string $moduleId = 'stripe';
    public string $allowedAppName = 'NGauge Commerce';
    public string $secretKey = '';
    public string $webhookSigningSecret = '';
    public string $apiBaseUrl = 'https://api.stripe.com/v1';
    public ?string $stripeVersion = null;
    public int $timeout = 30;
    public int $webhookTolerance = 300;
    public bool $debug = false;

    public $controllerNamespace = 'PortalPeople\stripe\controllers';

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

        $config = Yii::$app->params['plugins']['stripe'] ?? [];
        if (!is_array($config)) {
            return;
        }

        $this->secretKey = (string) ($config['secretKey'] ?? $this->secretKey);
        $this->webhookSigningSecret = (string) ($config['webhookSigningSecret'] ?? $this->webhookSigningSecret);
        $this->apiBaseUrl = (string) ($config['apiBaseUrl'] ?? $this->apiBaseUrl);
        $this->stripeVersion = $config['stripeVersion'] ?? $this->stripeVersion;
        $this->timeout = (int) ($config['timeout'] ?? $this->timeout);
        $this->webhookTolerance = (int) ($config['webhookTolerance'] ?? $this->webhookTolerance);
        $this->debug = (bool) ($config['debug'] ?? $this->debug);
    }

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

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

        if ($app->name === $this->allowedAppName && $app->has('urlManager')) {
            $app->urlManager->addRules([
                "{$this->id}/api/<action:[\\w\\-]+>" => "{$this->id}/api/<action>",
                "{$this->id}/webhook/<action:[\\w\\-]+>" => "{$this->id}/webhook/<action>",
                "{$this->id}/hostedpage/<action:[\\w\\-]+>" => "{$this->id}/hostedpage/<action>",
                "{$this->id}/config/<action:[\\w\\-]+>" => "{$this->id}/config/<action>",
            ], false);
        }
    }
}
