<?php
declare(strict_types=1);

namespace Celena\Module\Webhooks;

use Celena\Core\Container;
use Celena\Core\Database\Connection;
use Celena\Core\Queue\JobInterface;

final class SendWebhookJob implements JobInterface
{
    public function handle(Container $container, array $payload): void
    {
        $url = (string) ($payload['url'] ?? '');
        $secret = (string) ($payload['secret'] ?? '');
        $body = (array) ($payload['payload'] ?? []);
        $webhookId = (int) ($payload['webhook_id'] ?? 0);
        if ($url === '') return;

        $status = WebhookDispatcher::send($url, $secret, $body);

        if ($webhookId > 0) {
            /** @var Connection $conn */
            $conn = $container->make(Connection::class);
            $conn->builder('celena_webhooks')->where('id', '=', $webhookId)->update([
                'last_status' => $status,
                'last_sent_at' => date('Y-m-d H:i:s'),
            ]);
        }
        if ($status < 200 || $status >= 300) {
            throw new \RuntimeException("Webhook HTTP $status");
        }
    }
}
