<?php

namespace App\Http\Middleware;

use Illuminate\Http\Request;
use Illuminate\Routing\Middleware\ThrottleRequests;

class CustomThrottle extends ThrottleRequests
{
    /**
     * Create a 'too many attempts' exception.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $key
     * @param  int  $maxAttempts
     * @param  int|null  $retryAfter
     * @return \Symfony\Component\HttpFoundation\Response
     */
    protected function buildException($request, $key, $maxAttempts, $retryAfter = null)
    {
        $retryAfterSeconds = $retryAfter ?? 60;
        $headers = $this->getHeaders($maxAttempts, $retryAfterSeconds);

        $message = "Terlalu banyak permintaan. Silakan tunggu {$retryAfterSeconds} detik sebelum mencoba lagi.";

        // Response structure yang akan ditangkap frontend
        $responseData = [
            'success' => false,
            'message' => $message,
            'retry_after' => $retryAfterSeconds,
            'toast' => [
                'type' => 'error',
                'message' => $message,
                'duration' => 5000,
            ],
        ];

        // Jika request mengharapkan JSON atau adalah request AJAX
        if ($request->expectsJson() || $request->ajax() || $request->wantsJson()) {
            return response()->json($responseData, 429, $headers);
        }

        // Jika request Inertia, kembalikan JSON juga agar bisa ditangani client-side
        if ($request->header('X-Inertia')) {
            return response()->json($responseData, 429, $headers);
        }

        // Untuk request biasa, kembalikan redirect dengan flash message
        $redirect = redirect()->back();
        if ($redirect) {
            return $redirect
                ->with('error', $message)
                ->with('toast', $responseData['toast']);
        }

        // Fallback jika redirect gagal
        return response()->json($responseData, 429, $headers);
    }
}
