<?php

declare(strict_types=1);

namespace portalpeople\messagingwebhooks;

use portalpeople\messagingwebhooks\services\SendgridWebhookService;
use portalpeople\messagingwebhooks\services\SendinblueWebhookService;
use Yii;
use yii\base\BootstrapInterface;
use yii\web\Application as WebApplication;

/**
 * NGauge Messaging Webhooks Module
 *
 * Handles inbound webhook events from Sendgrid and Sendinblue (Brevo).
 *
 * Configuration (params.php):
 * 'plugins' => [
 *     'messaging-webhooks' => [
 *         'enabled' => true,
 *         // Optional: Sendgrid signed-event webhook verification key
 *         'sendgridSigningKey' => '',
 *     ],
 * ]
 */
class Module extends \yii\base\Module implements BootstrapInterface
{
    /** @var string Unique module identifier used in params config */
    public string $moduleId = 'messaging-webhooks';

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

    /** @var string|null Sendgrid signed-event verification key (optional) */
    public ?string $sendgridSigningKey = null;

    private ?SendgridWebhookService $sendgridWebhookService = null;
    private ?SendinblueWebhookService $sendinblueWebhookService = null;

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

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

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

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

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

        $app->getUrlManager()->addRules([
            'GET v1/sendgrid'        => 'messaging-webhooks/api/sendgrid/index',
            'POST v1/sendgrid'       => 'messaging-webhooks/api/sendgrid/create',
            'GET v1/sendinblue/hook' => 'messaging-webhooks/api/sendinblue/hook',
            'POST v1/sendinblue'     => 'messaging-webhooks/api/sendinblue/create',
            'PUT v1/sendinblue'      => 'messaging-webhooks/api/sendinblue/update',
        ], false);
    }

    public function getSendgridWebhookService(): SendgridWebhookService
    {
        if ($this->sendgridWebhookService === null) {
            $this->sendgridWebhookService = new SendgridWebhookService();
        }

        return $this->sendgridWebhookService;
    }

    public function getSendinblueWebhookService(): SendinblueWebhookService
    {
        if ($this->sendinblueWebhookService === null) {
            $this->sendinblueWebhookService = new SendinblueWebhookService();
        }

        return $this->sendinblueWebhookService;
    }
}
