<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Controller\Trait;

use Doctrine\Persistence\ManagerRegistry;
use Mautic\UserBundle\Entity\User;

/**
 * Provides owner choices for use in deal-related controllers.
 */
trait OwnerChoicesTrait
{
    /**
     * @return array<string, int>
     */
    private function buildOwnerChoices(ManagerRegistry $managerRegistry, ?int $selectedOwnerId = null): array
    {
        $entries = [];
        $seenIds = [];

        foreach ($managerRegistry->getRepository(User::class)->findAll() as $owner) {
            $ownerId = $owner->getId();
            if (null === $ownerId) {
                continue;
            }

            $entries[] = [
                'id' => $ownerId,
                'label' => sprintf('%s (#%d)', $this->formatOwnerName($owner), $ownerId),
            ];
            $seenIds[$ownerId] = true;
        }

        if (null !== $selectedOwnerId && !isset($seenIds[$selectedOwnerId])) {
            $entries[] = [
                'id' => $selectedOwnerId,
                'label' => sprintf('User #%d (missing)', $selectedOwnerId),
            ];
        }

        usort($entries, static fn (array $left, array $right): int => strcasecmp($left['label'], $right['label']));

        $choices = [];
        foreach ($entries as $entry) {
            $choices[$entry['label']] = $entry['id'];
        }

        return $choices;
    }

    private function formatOwnerName(User $owner): string
    {
        $name = method_exists($owner, 'getName') ? (string) $owner->getName() : '';
        if ('' !== trim($name)) {
            return trim($name);
        }

        if (method_exists($owner, 'getUserIdentifier')) {
            $identifier = (string) $owner->getUserIdentifier();
            if ('' !== trim($identifier)) {
                return trim($identifier);
            }
        }

        return sprintf('User #%d', $owner->getId());
    }
}
