<?php

declare(strict_types=1);

namespace portalpeople\messagingwebhooks\services;

use Yii;

/**
 * SendinblueWebhookService
 *
 * Processes inbound Sendinblue (Brevo) webhook payloads and persists them.
 * Extracted from api/modules/v1/controllers/SendinblueController.
 */
class SendinblueWebhookService
{
    /**
     * Acknowledge a webhook ping (actionHook).
     *
     * Sendinblue sends a verification ping to validate the endpoint.
     * Return 200 with no body to confirm registration.
     */
    public function acknowledgeHook(): void
    {
        // Intentionally empty — 200 response is sufficient for Sendinblue verification
    }

    /**
     * Persist a subscriber record from a Sendinblue webhook create event.
     *
     * @param array<string, mixed> $params  Post body params
     * @return array<string, mixed>
     */
    public function processCreate(array $params): array
    {
        $hook = new \backend\models\Mailinglistbe();

        if ($hook->load($params) && $hook->save()) {
            return ['status' => 200, 'message' => 'Saved'];
        }

        Yii::warning('Sendinblue webhook save failed: ' . json_encode($hook->errors), __CLASS__);
        return ['status' => 100, 'message' => $hook->errors];
    }
}
