<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Wishlist;

use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Repository\OfferRepositoryInterface;
use Symfony\Component\Uid\Uuid;

/**
 * Resolves the offer references that wishlists store — an offer's base58 UUID
 * (the format used since the UUID migration) or a legacy integer offer id
 * (entries / share links created before it) — to {@see OfferInterface}, and
 * back to the canonical base58 ref.
 *
 * Shared by {@see \Ferienpass\CmsBundle\Controller\Page\FavoritesController}
 * (share links) and {@see WishlistSynchronizer} (account sync) so the two
 * stay consistent.
 */
class OfferRefResolver
{
    public function __construct(private readonly OfferRepositoryInterface $offers)
    {
    }

    public function resolve(string $ref): ?OfferInterface
    {
        $ref = trim($ref);
        if ('' === $ref) {
            return null;
        }

        if (ctype_digit($ref)) {
            return $this->offers->find((int) $ref);
        }

        try {
            return $this->offers->findByUuid(Uuid::fromBase58($ref));
        } catch (\InvalidArgumentException) {
            return null;
        }
    }

    /**
     * The canonical reference to store for an offer: its base58 UUID.
     */
    public function canonicalRef(OfferInterface $offer): string
    {
        return $offer->getUuid()->toBase58();
    }
}
