<?php

namespace App\Http\Middleware;

use App\Support\UsernamePolicy;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class NormalizeUsername
{
    public function handle(Request $request, Closure $next): Response
    {
        $payload = $request->all();

        if (array_key_exists('username', $payload)) {
            $payload['username'] = UsernamePolicy::normalize((string) $payload['username']);
        }

        if (array_key_exists('old_username', $payload)) {
            $payload['old_username'] = UsernamePolicy::normalize((string) $payload['old_username']);
        }

        $request->merge($payload);

        return $next($request);
    }
}
