<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\PaystackService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PaystackWebhookController extends Controller
{
    public function __invoke(Request $request, PaystackService $paystack): JsonResponse
    {
        abort_unless($paystack->validSignature($request->getContent(), $request->header('x-paystack-signature')), 401);
        $event = $request->json()->all();
        if (($event['event'] ?? null) === 'charge.success' && isset($event['data']['reference'])) {
            $paystack->fulfill($event['data']['reference'], $event['data']);
        }

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