<?php

namespace App\Support;

use Illuminate\Support\Arr;
use Illuminate\Support\Str;

class LocaleConfig
{
    /**
     * Return configured locales from env/config as provided (may include region codes).
     * @return array<int, string>
     */
    public static function configured(): array
    {
        $configured = array_filter(array_map(
            static fn ($value) => trim((string) $value),
            explode(',', (string) env('APP_SUPPORTED_LOCALES', ''))
        ));

        $baseLocales = array_filter([
            config('app.locale'),
            config('app.fallback_locale'),
        ]);

        $fallback = ['de', 'en'];

        return array_values(array_unique([
            ...$configured,
            ...$baseLocales,
            ...$fallback,
        ]));
    }

    /**
     * Return normalized short codes (language only, lowercase).
     * @return array<int, string>
     */
    public static function normalized(): array
    {
        return collect(static::configured())
            ->map(fn (string $code) => Str::of($code)->lower()->before('-')->before('_')->toString())
            ->filter()
            ->unique()
            ->values()
            ->all();
    }

    /**
     * Pattern for route constraints: accept both configured and normalized variants.
     */
    public static function routePattern(): string
    {
        $all = collect(array_merge(static::configured(), static::normalized()))
            ->map(fn (string $code) => preg_quote($code, '/'))
            ->unique()
            ->values()
            ->all();

        return implode('|', $all);
    }

    /**
     * Canonicalize any incoming locale to a normalized short code if supported, otherwise fallback.
     */
    public static function canonicalize(?string $locale): string
    {
        $normalized = static::normalized();
        $fallback = Arr::first($normalized, default: 'de');

        if (! $locale) {
            return $fallback;
        }

        $short = Str::of($locale)->lower()->before('-')->before('_')->toString();

        return in_array($short, $normalized, true) ? $short : $fallback;
    }
}
