<?php

declare(strict_types=1);

namespace App\Framework\Webhook\Processing;

use App\Framework\Exception\WebhookException;
use App\Framework\Logging\Logger;
use App\Framework\Webhook\Jobs\WebhookJob;
use App\Framework\Webhook\Sending\WebhookSender;

/**
 * Processes webhook jobs from the queue
 * Integrates with framework's queue worker system
 */
final readonly class WebhookJobProcessor
{
    public function __construct(
        private WebhookSender $webhookSender,
        private Logger $logger
    ) {
    }

    /**
     * Process webhook job from queue
     * Called by queue worker when job is dequeued
     */
    public function process(object $job): void
    {
        if (! $job instanceof WebhookJob) {
            throw new WebhookException('Invalid job type for webhook processor');
        }

        $this->logger->debug('Processing webhook job', [
            'job_id' => $job->getJobId(),
            'url' => $job->url,
            'provider' => $job->provider->toString(),
        ]);

        try {
            // Execute the webhook job
            $job->execute($this->webhookSender, $this->logger);

        } catch (\Exception $e) {
            $this->logger->error('Webhook job processing failed', [
                'job_id' => $job->getJobId(),
                'url' => $job->url,
                'provider' => $job->provider->toString(),
                'error' => $e->getMessage(),
            ]);

            // Re-throw to let queue handle failure (retry/dead letter)
            throw $e;
        }
    }

    /**
     * Check if processor can handle the job type
     */
    public function canProcess(object $job): bool
    {
        return $job instanceof WebhookJob;
    }

    /**
     * Get processor name for queue configuration
     */
    public function getName(): string
    {
        return 'webhook';
    }

    /**
     * Get processor priority for job routing
     */
    public function getPriority(): int
    {
        return 0; // Normal priority
    }
}
