<?php

declare(strict_types=1);

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * WHMCS webhook isteklerinde HMAC-SHA256 doğrulaması.
 *
 * Header: X-Onoxsoft-Signature: sha256=<hex>
 * Secret: config('onoxsoft.whmcs.hmac_secret') (.env)
 * Imzalanan: timestamp + body (timestamp tolerans: 5 dakika)
 */
class VerifyWhmcsHmac
{
    public function handle(Request $request, Closure $next): Response
    {
        $secret = (string) config('onoxsoft.whmcs.hmac_secret');
        if ($secret === '') {
            return response()->json([
                'error' => 'WHMCS HMAC secret yapılandırılmamış.',
            ], 503);
        }

        $signature = $request->header('X-Onoxsoft-Signature', '');
        $timestamp = $request->header('X-Onoxsoft-Timestamp', '');

        if ($signature === '' || $timestamp === '') {
            return response()->json(['error' => 'Eksik HMAC header.'], 401);
        }

        // Replay koruması — 5 dk tolerans
        if (abs(time() - (int) $timestamp) > 300) {
            return response()->json(['error' => 'Timestamp aralık dışı.'], 401);
        }

        $expected = 'sha256='.hash_hmac('sha256', $timestamp.'.'.$request->getContent(), $secret);

        if (! hash_equals($expected, $signature)) {
            return response()->json(['error' => 'HMAC doğrulama başarısız.'], 401);
        }

        return $next($request);
    }
}
