<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Marketing;

use CpCreation\VitiCore\Cart\Model\Cart;

final readonly class ReviewAuthorDisplayNameFormatter
{
    public function format(Cart $cart, string $fallback): string
    {
        $firstname = $this->normalizeName($cart->getFirstname());
        $lastname = $this->normalizeName($cart->getLastname());
        $lastInitial = null !== $lastname
            ? mb_strtoupper(mb_substr($lastname, 0, 1)) . '.'
            : null;

        $displayName = mb_trim(implode(' ', array_filter(
            [$firstname, $lastInitial],
            static fn(?string $part): bool => null !== $part,
        )));

        return '' !== $displayName
            ? mb_substr($displayName, 0, 80)
            : mb_substr(mb_trim($fallback), 0, 80);
    }

    private function normalizeName(?string $name): ?string
    {
        if (null === $name || '' === mb_trim($name)) {
            return null;
        }

        return mb_convert_case(mb_trim($name), \MB_CASE_TITLE, 'UTF-8');
    }
}
