<?php

declare(strict_types=1);

namespace Apexl\Io\Routing;

use InvalidArgumentException;

/**
 * A route pattern that could never match what it was meant to.
 *
 * Slim does not normalise patterns. A path with no leading slash is registered exactly as
 * given, and no request can match it — request targets always begin with one — so the route
 * appears in `routes:dump`, looks registered, and answers 404 forever.
 *
 * Inside a group it is worse than useless: `RouteCollectorProxy::map()` concatenates, so a
 * group on `/admin` holding a route on `users` registers `/adminusers`. That is a real,
 * reachable route at a path nobody intended, and `/admin/users` 404s.
 *
 * Neither is reported by anything, which is why this is raised where the route is declared.
 */
final class RoutePatternException extends InvalidArgumentException
{
    public static function for(string $pattern, string $groupPattern = ''): self
    {
        if ($groupPattern !== '') {
            return new self(sprintf(
                'Route pattern \'%s\' must start with "/" — inside the group \'%s\' it would '
                . 'register \'%s\' rather than \'%s/%s\'.',
                $pattern,
                $groupPattern,
                $groupPattern . $pattern,
                rtrim($groupPattern, '/'),
                $pattern,
            ));
        }

        return new self(sprintf(
            'Route pattern \'%s\' must start with "/"; as given, no request path can match it.',
            $pattern,
        ));
    }
}
