<?php

declare(strict_types=1);

namespace App\Http\Middleware;

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

class AccountLockout
{
    /** Maximum failed attempts before account lock. */
    private const MAX_ATTEMPTS = 10;

    /** Cache TTL for the lock (seconds). */
    private const LOCK_TTL = 3600; // 1 saat

    public function handle(Request $request, Closure $next): Response
    {
        if ($request->isMethod('POST') && $request->routeIs('login')) {
            $key = $this->cacheKey($request->input('email', ''));
            $attempts = cache()->get($key, 0);

            if ($attempts >= self::MAX_ATTEMPTS) {
                return response()->json([
                    'message' => 'Hesabınız 1 saat süreyle kilitlendi.',
                ], 423);
            }
        }

        $response = $next($request);

        // Track failed login attempts (HTTP 422 = validation / wrong credentials)
        if ($request->routeIs('login') && $response->getStatusCode() === 422) {
            $key = $this->cacheKey($request->input('email', ''));
            $current = cache()->get($key, 0);
            cache()->put($key, $current + 1, now()->addSeconds(self::LOCK_TTL));
        }

        return $response;
    }

    private function cacheKey(string $email): string
    {
        return 'failed-login:'.strtolower(trim($email));
    }
}
