<?php

namespace portalpeople\stripe\controllers\api;

use portalpeople\stripe\components\WebhookSignatureVerifier;
use portalpeople\stripe\Module;
use Yii;
use yii\web\Controller;
use yii\web\Response;

class WebhookController extends Controller
{
    public $enableCsrfValidation = false;

    private WebhookSignatureVerifier $verifier;

    public function init(): void
    {
        parent::init();
        $this->verifier = new WebhookSignatureVerifier();
    }

    public function actionReceive(): array
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        if (!Yii::$app->request->isPost) {
            Yii::$app->response->statusCode = 405;
            return ['error' => 'POST required.'];
        }

        /** @var Module $module */
        $module = $this->module;
        $payload = (string) Yii::$app->request->rawBody;
        $signatureHeader = (string) Yii::$app->request->headers->get('Stripe-Signature', '');

        $isValid = $this->verifier->verify(
            $payload,
            $signatureHeader,
            $module->webhookSigningSecret,
            $module->webhookTolerance
        );

        if (!$isValid) {
            Yii::$app->response->statusCode = 400;
            return ['error' => 'Invalid webhook signature.'];
        }

        $event = json_decode($payload, true);
        if (!is_array($event)) {
            Yii::$app->response->statusCode = 400;
            return ['error' => 'Invalid JSON payload.'];
        }

        if ($module->debug) {
            Yii::info('[stripe] webhook received: ' . ($event['type'] ?? 'unknown'), __CLASS__);
        }

        return [
            'received' => true,
            'eventId' => $event['id'] ?? null,
            'eventType' => $event['type'] ?? null,
        ];
    }
}
