<?php

namespace App\Http\Middleware;

use Closure;

class ThrottleApi
{
    public function handle($request, Closure $next)
    {
        $limit = (int)(env('API_RATE_LIMIT', 60));
        $window = (int)(env('API_RATE_WINDOW', 60));

        $ip = $request->ip() ?? $request->server('REMOTE_ADDR', 'unknown');
        $file = storage_path('framework/api_throttle.json');
        $dir = dirname($file);

        if (!is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }

        // Load và dọn dữ liệu cũ
        $data = [];
        if (file_exists($file)) {
            $raw = @file_get_contents($file);
            $data = $raw ? json_decode($raw, true) ?? [] : [];
        }

        $now = time();
        foreach ($data as $k => $v) {
            if (isset($v['ts']) && ($now - $v['ts']) > $window) {
                unset($data[$k]);
            }
        }

        if (!isset($data[$ip])) {
            $data[$ip] = ['count' => 1, 'ts' => $now];
        } else {
            $data[$ip]['count']++;
        }

        @file_put_contents($file, json_encode($data), LOCK_EX);

        if ($data[$ip]['count'] > $limit) {
            return response()->json(['message' => 'Rate limit exceeded'], 429);
        }

        return $next($request);
    }
}
