<?php

namespace PortalPeople\virtualstock\jobs;

use Yii;
use yii\base\BaseObject;
use yii\queue\JobInterface;
use PortalPeople\virtualstock\Module;
use PortalPeople\virtualstock\services\WebhookService;
use PortalPeople\virtualstock\exceptions\ValidationException;

/**
 * Queue job that processes a single inbound VirtualStock webhook event.
 *
 * The raw body and signature header are stored on the job so that signature
 * verification is re-run inside the worker, ensuring integrity is checked even
 * when processing is deferred.
 *
 * Push via:
 *   Yii::$app->get($module->queueComponent)->push(new ProcessWebhookJob([
 *       'rawBody'         => $rawBody,
 *       'signatureHeader' => $signatureHeader,
 *   ]));
 */
class ProcessWebhookJob extends BaseObject implements JobInterface
{
    /** Raw HTTP request body received from VirtualStock. */
    public string $rawBody = '';

    /** Value of the X-Virtualstock-Signature header. */
    public string $signatureHeader = '';

    /**
     * @inheritdoc
     */
    public function execute($queue): void
    {
        /** @var Module|null $module */
        $module = Yii::$app->getModule('virtualstock');

        if ($module === null || !$module->isConfigured()) {
            Yii::warning('ProcessWebhookJob: module not configured — skipping.', 'virtualstock');
            return;
        }

        /** @var WebhookService $service */
        $service = Yii::createObject([
            'class'         => WebhookService::class,
            'webhookSecret' => $module->webhookSecret ?? '',
        ]);

        try {
            $service->process($this->rawBody, $this->signatureHeader);
        } catch (ValidationException $e) {
            Yii::error(
                'ProcessWebhookJob validation error: ' . $e->getMessage(),
                'virtualstock'
            );
            // Do not re-throw — a validation failure is permanent; retrying won't help.
        } catch (\Throwable $e) {
            Yii::error(
                'ProcessWebhookJob unexpected error: ' . $e->getMessage(),
                'virtualstock'
            );
            // Re-throw so the queue can retry (e.g. transient DB/cache failures).
            throw $e;
        }
    }
}
