<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Export\Helper;

use Chill\MainBundle\Templating\TranslatableStringHelperInterface;

/**
 * This class provides support for showing translatable string into list or exports.
 *
 * (note: the name of the class contains "ExportLabelHelper" to give a distinction
 * with TranslatableStringHelper.)
 */
class TranslatableStringExportLabelHelper
{
    public function __construct(private readonly TranslatableStringHelperInterface $translatableStringHelper) {}

    public function getLabel(string $key, array $values, string $header)
    {
        return function ($value) use ($header) {
            if ('_header' === $value) {
                return $header;
            }

            if (null === $value) {
                return '';
            }

            return $this->translatableStringHelper->localize(json_decode((string) $value, true, 512, JSON_THROW_ON_ERROR));
        };
    }

    public function getLabelMulti(string $key, array $values, string $header)
    {
        return function ($value) use ($header) {
            if ('_header' === $value) {
                return $header;
            }

            if (null === $value) {
                return '';
            }

            $decoded = json_decode((string) $value, true, 512, JSON_THROW_ON_ERROR);

            return implode(
                '|',
                array_unique(
                    array_map(
                        fn (array $translatableString) => $this->translatableStringHelper->localize($translatableString),
                        array_filter($decoded, static fn ($elem) => null !== $elem)
                    )
                )
            );
        };
    }
}
