<?php

declare(strict_types=1);

namespace portalpeople\messagingwebhooks\controllers\api;

use portalpeople\messagingwebhooks\Module;
use Yii;
use yii\rest\Controller;

/**
 * @OA\Tag(
 *     name="Sendinblue Webhooks",
 *     description="Inbound Sendinblue (Brevo) webhook endpoint"
 * )
 */
class SendinblueController extends Controller
{
    /**
     * @OA\Get(
     *     path="/v1/sendinblue/hook",
     *     tags={"Sendinblue Webhooks"},
     *     summary="Webhook verification ping",
     *     @OA\Response(response=200, description="OK")
     * )
     */
    public function actionHook(): void
    {
        Yii::$app->response->format = 'json';
        Yii::$app->response->statusCode = 200;
    }

    /**
     * @OA\Post(
     *     path="/v1/sendinblue",
     *     tags={"Sendinblue Webhooks"},
     *     summary="Receive Sendinblue subscriber create event",
     *     @OA\Response(response=200, description="Saved"),
     *     @OA\Response(response=503, description="Module unavailable")
     * )
     */
    public function actionCreate(): array
    {
        Yii::$app->response->format = 'json';

        /** @var Module|null $module */
        $module = Yii::$app->getModule('messaging-webhooks');

        if ($module === null || !method_exists($module, 'getSendinblueWebhookService')) {
            Yii::error('messaging-webhooks module unavailable in SendinblueController::actionCreate', __CLASS__);
            Yii::$app->response->statusCode = 503;
            return ['status' => 503, 'message' => 'Service unavailable'];
        }

        return $module->getSendinblueWebhookService()->processCreate(Yii::$app->request->post() ?? []);
    }

    /**
     * @OA\Put(
     *     path="/v1/sendinblue",
     *     tags={"Sendinblue Webhooks"},
     *     summary="Receive Sendinblue subscriber update event",
     *     @OA\Response(response=200, description="OK")
     * )
     */
    public function actionUpdate(): string
    {
        return 'Good';
    }
}
