<?php

namespace App\Http\Controllers\Stripe;

use App\Http\Controllers\Controller;
use App\Services\StripeService;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Stripe\Exception\SignatureVerificationException;

class WebhookController extends Controller
{
    public function __invoke(Request $request, StripeService $stripe): Response
    {
        $payload   = $request->getContent();
        $signature = $request->header('Stripe-Signature', '');

        try {
            $stripe->handleWebhook($payload, $signature);
        } catch (SignatureVerificationException $e) {
            return response('Invalid signature', 400);
        } catch (\Throwable $e) {
            report($e);
            return response('Webhook error: ' . $e->getMessage(), 500);
        }

        return response('OK', 200);
    }
}
