<?php

declare(strict_types=1);

namespace ImovelZapAi\Billing\Presentation\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use ImovelZapAi\Billing\Application\Actions\SyncSubscriptionFromWebhookAction;

final class MercadoPagoWebhookController
{
    public function __invoke(Request $request, SyncSubscriptionFromWebhookAction $action): JsonResponse
    {
        $secret = (string) config('billing.mercadopago.webhook_secret', '');
        if ($secret !== '') {
            $incoming = (string) ($request->header('X-Signature')
                ?? $request->header('x-webhook-secret')
                ?? $request->query('secret', ''));

            if (! hash_equals($secret, $incoming)) {
                return response()->json(['ok' => false], 401);
            }
        }

        $action->execute($request->all());

        return response()->json(['ok' => true]);
    }
}
