<?php

declare(strict_types=1);

namespace App\Middleware;

use Closure;
use App\Support\RouteArgumentParser;
use App\Support\HashkeyResolver;
use Hypervel\Http\Request;

/**
 * DecodeRouteArgumentMiddleware automatically parses URL arguments and attaches them to the request.
 * 
 * This middleware handles URLs in format: /page-name--h:HASHKEY or /page-name--e:ENCODED_PAYLOAD
 * The parsed data is made available as $request->decodedRoute
 */
class DecodeRouteArgumentMiddleware
{
    /**
     * Handle the request and decode route arguments.
     *
     * @param \Hypervel\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Get the path info from the request
        $path = $request->path();
        
        // Use RouteArgumentParser to parse the URL argument
        $parser = new RouteArgumentParser();
        $parsedData = $parser->parseArgument($path);
        
        // Extract hashkey and payload based on the parsed type
        $hashkey = null;
        $payload = null;
        
        if ($parser->isHashFormat($path)) {
            $hashkey = $parsedData['value'] ?? null;
        } elseif ($parser->isPayloadFormat($path)) {
            $payload = $parsedData['value'] ?? null;
        }
        
        // Attach parsed data to request for easy access
        $request->merge([
            'decodedRoute' => [
                'slug' => $parsedData['slug'] ?? '',
                'type' => $parsedData['type'] ?? null,
                'hashkey' => $hashkey,
                'payload' => $payload,
            ],
        ]);

        // Continue to the next middleware
        return $next($request);
    }
}
