<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Routing;

/**
 * The locales the route collections are prefixed with.
 *
 * German is the fallback and carries no prefix; every other locale prefixes the
 * path with its own code. This list mirrors the `prefix` maps in
 * `admin-bundle/config/routes.yaml` and `cms-bundle/config/routes.php` — and
 * {@see \Ferienpass\CmsBundle\Routing\LocaleRouteProviderDecorator::MAP}, which
 * a test keeps in sync.
 *
 * It matters here because a URL has to be split into "locale prefix" and "the
 * rest" to move the admin between `<host>/admin/…` and `<admin-host>/…`, and
 * guessing at `[a-z]{2,3}` would mistake an admin path segment (`/api`) for a
 * language.
 */
final class Locales
{
    /**
     * @var list<string>
     */
    public const array ALL = [
        'de', 'nl', 'en', 'ar', 'ru', 'uk', 'tr', 'pl', 'sq', 'ku',
        'es', 'fr', 'pt', 'sw', 'prs', 'zh', 'sr', 'hr', 'bs',
    ];

    /** The locale served without a path prefix. */
    public const string DEFAULT = 'de';

    /**
     * Splits a path into its locale prefix and the remainder.
     *
     * `/nl/admin/angebote` → `['/nl', '/admin/angebote']`
     * `/admin/angebote`    → `['', '/admin/angebote']`
     * `/nl`                → `['/nl', '/']`
     *
     * @return array{string, string}
     */
    public static function splitPrefix(string $path): array
    {
        if (!preg_match('#^/([a-z]{2,3})(/.*)?$#', $path, $m)) {
            return ['', $path];
        }

        if (self::DEFAULT === $m[1] || !\in_array($m[1], self::ALL, true)) {
            return ['', $path];
        }

        return ['/'.$m[1], ($m[2] ?? '') ?: '/'];
    }
}
