<?php

namespace App\Support;

final class LocalizedName
{
    /**
     * @param  array<string, string>|string|null  $names
     */
    public static function resolve(array|string|null $names, ?string $locale = null): string
    {
        if ($names === null || $names === '') {
            return '';
        }

        if (is_string($names)) {
            $decoded = json_decode($names, true);

            return is_array($decoded) ? self::resolve($decoded, $locale) : $names;
        }

        $locale = $locale ?? app()->getLocale();

        return $names[$locale]
            ?? $names['en']
            ?? (string) reset($names);
    }

    public static function fromModel(object $row, string $column = 'name'): string
    {
        $value = $row->{$column} ?? null;

        if (is_array($value)) {
            return self::resolve($value);
        }

        return self::resolve(is_string($value) ? $value : null);
    }
}
