<?php

namespace App\Modules\Integrations\Platform\Services;

use App\Modules\Integrations\Platform\Models\IntegrationWebhook;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

final class WebhookTestDeliveryService
{
    public function __construct(private readonly WebhookSigner $signer) {}

    /**
     * @return array{ok:bool, http_status:?int, error:?string, request_id:string}
     */
    public function sendTest(IntegrationWebhook $webhook): array
    {
        $name = (string) config('integrations.webhooks.test_event_name', 'integration.test');
        $version = (int) config('integrations.webhooks.test_event_version', 1);
        $fakeId = (string) Str::uuid();
        $payload = [
            'id' => $fakeId,
            'name' => $name,
            'version' => $version,
            'occurred_at' => now()->toISOString(),
            'payload' => ['kind' => 'ping'],
        ];

        $sig = $this->signer->sign((string) $webhook->secret_enc, $fakeId, $payload);
        $rid = (string) Str::uuid();

        try {
            $resp = Http::timeout(8)
                ->withHeaders([
                    'Content-Type' => 'application/json',
                    'User-Agent' => 'SaaS-ERP Webhooks (test)',
                    'X-Webhook-Id' => $fakeId,
                    'X-Webhook-Timestamp' => (string) $sig['timestamp'],
                    'X-Webhook-Signature' => $sig['signature'],
                    'X-Request-Id' => $rid,
                ])
                ->post((string) $webhook->url, $payload);

            return [
                'ok' => $resp->successful(),
                'http_status' => $resp->status(),
                'error' => $resp->successful() ? null : 'HTTP '.$resp->status(),
                'request_id' => $rid,
            ];
        } catch (\Throwable $e) {
            return ['ok' => false, 'http_status' => null, 'error' => $e->getMessage(), 'request_id' => $rid];
        }
    }
}
