<?php

namespace App\Services;

use App\Models\Setting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class WebhookService
{
    public static function fire(string $event, array $payload): void
    {
        $url    = Setting::get('webhook_url');
        $secret = Setting::get('webhook_secret');

        if (!$url) return;

        $enabledEvents = Setting::get('webhook_events', '');
        $allowed = array_filter(array_map('trim', explode(',', $enabledEvents)));

        // Se nenhum evento configurado, dispara tudo
        if (!empty($allowed) && !in_array($event, $allowed)) return;

        $body = json_encode([
            'event'     => $event,
            'timestamp' => now()->toIso8601String(),
            'payload'   => $payload,
        ]);

        $headers = [
            'Content-Type' => 'application/json',
            'X-Opcon-Event' => $event,
        ];

        if ($secret) {
            $headers['X-Opcon-Signature'] = 'sha256=' . hash_hmac('sha256', $body, $secret);
        }

        try {
            Http::withHeaders($headers)->timeout(8)->send('POST', $url, ['body' => $body]);
        } catch (\Throwable $e) {
            Log::warning("Webhook '{$event}' falhou: " . $e->getMessage());
        }
    }
}
