<?php

declare(strict_types=1);

namespace portalpeople\messagingwebhooks\services;

use Yii;

/**
 * SendgridWebhookService
 *
 * Processes inbound Sendgrid event webhook payloads and persists them.
 * Extracted from api/modules/v1/controllers/SendgridController::actionCreate().
 *
 * Note: Sendgrid supports webhook signature verification via the Signed Event
 * Webhook feature. Add signature validation here when the signing key is
 * available (Yii::$app->params['plugins']['messaging-webhooks']['sendgridSigningKey']).
 */
class SendgridWebhookService
{
    /**
     * Persist a batch of Sendgrid webhook events.
     *
     * @param array<int, array<string, mixed>> $events  Decoded JSON payload from Sendgrid
     * @return string  JSON-encoded result
     */
    public function processEvents(array $events): string
    {
        foreach ($events as $ele) {
            $hook = new \backend\models\Sgwebhooksbe();

            foreach ($ele as $field => $value) {
                // Sendgrid uses 'ip'; the model column is 'ipaddress'
                if ($field === 'ip') {
                    $field = 'ipaddress';
                }

                // url_offset is a nested structure — store as JSON
                if ($field === 'url_offset') {
                    $value = json_encode($value);
                }

                $hook->$field = $value;
            }

            if (!$hook->save()) {
                Yii::warning('Sendgrid webhook save failed: ' . json_encode($hook->errors), __CLASS__);
            }
        }

        return json_encode(['status' => 200, 'message' => 'Good']);
    }
}
