<?php

declare(strict_types=1);

namespace portalpeople\messagingwebhooks\controllers\api;

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

/**
 * @OA\Tag(
 *     name="Sendgrid Webhooks",
 *     description="Inbound Sendgrid event webhook endpoint"
 * )
 */
class SendgridController extends Controller
{
    /**
     * @OA\Get(
     *     path="/v1/sendgrid",
     *     tags={"Sendgrid Webhooks"},
     *     summary="Webhook health check",
     *     @OA\Response(response=200, description="OK")
     * )
     */
    public function actionIndex(): string
    {
        return 'BBEEEEPPPPPPP';
    }

    /**
     * @OA\Post(
     *     path="/v1/sendgrid",
     *     tags={"Sendgrid Webhooks"},
     *     summary="Receive Sendgrid event batch",
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(type="array", @OA\Items(type="object"))
     *     ),
     *     @OA\Response(response=200, description="Accepted"),
     *     @OA\Response(response=503, description="Module unavailable")
     * )
     */
    public function actionCreate(): string
    {
        /** @var Module|null $module */
        $module = Yii::$app->getModule('messaging-webhooks');

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

        $data = Yii::$app->request->post();

        if (!is_array($data)) {
            Yii::$app->response->statusCode = 400;
            return json_encode(['status' => 400, 'message' => 'Invalid payload']);
        }

        return $module->getSendgridWebhookService()->processEvents($data);
    }
}
