<?php

namespace App\Http\Controllers\Webhook;

use App\Http\Controllers\Controller;
use App\Models\Tenant;
use App\Services\VirtualAccountService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class PaystackWebhookController extends Controller
{
    public function __invoke(Request $request, VirtualAccountService $accounts): JsonResponse
    {
        $payload = $request->getContent();
        $tenant = $this->tenantFromSignature($payload, (string) $request->header('x-paystack-signature'));

        if (! $tenant) {
            return response()->json(['message' => 'Invalid webhook signature.'], 401);
        }

        $event = json_decode($payload, true);

        if (! is_array($event)) {
            return response()->json(['message' => 'Invalid webhook payload.'], 400);
        }

        $result = $accounts->creditPaystackTransfer($tenant, $event);

        return response()->json($result);
    }

    private function tenantFromSignature(string $payload, string $signature): ?Tenant
    {
        if ($signature === '') {
            return null;
        }

        return Tenant::query()
            ->where('status', 'active')
            ->get()
            ->first(function (Tenant $tenant) use ($payload, $signature): bool {
                $settings = $tenant->settings ?? [];

                if (($settings['payment_gateway_provider'] ?? 'none') !== 'paystack' || blank($settings['paystack_secret_key'] ?? null)) {
                    return false;
                }

                $expected = hash_hmac('sha512', $payload, (string) $settings['paystack_secret_key']);

                return hash_equals($expected, $signature);
            });
    }
}
