<?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\Tests\Controller\Frontend;

use Contao\CoreBundle\Exception\PageNotFoundException;
use Contao\CoreBundle\Framework\ContaoFramework;
use Ferienpass\CmsBundle\Controller\Frontend\RedirectShortUrlController;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Repository\OfferRepositoryInterface;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Uid\Uuid;

final class RedirectShortUrlControllerTest extends TestCase
{
    public function testInvokeWithPrivateLinkOfferThrows404(): void
    {
        $offer = $this->createMock(OfferInterface::class);
        $offer->method('isPublished')->willReturn(true);
        $offer->method('getPublish')->willReturn('private_link');

        $repository = $this->createMock(OfferRepositoryInterface::class);
        $repository->method('find')->with(123)->willReturn($offer);

        $framework = $this->createMock(ContaoFramework::class);

        $controller = new RedirectShortUrlController();

        $this->expectException(PageNotFoundException::class);

        $controller->__invoke(123, $repository, $framework);
    }

    public function testInvokeWithPublicOfferDoesNotThrow404(): void
    {
        $offer = $this->createMock(OfferInterface::class);
        $offer->method('isPublished')->willReturn(true);
        $offer->method('getPublish')->willReturn('public');
        $offer->method('isVariant')->willReturn(false);
        $offer->method('hasVariants')->willReturn(false);
        $offer->method('getAlias')->willReturn('some-alias');
        $uuid = Uuid::v7();
        $offer->method('getUuid')->willReturn($uuid);

        $repository = $this->createMock(OfferRepositoryInterface::class);
        $repository->method('find')->with(123)->willReturn($offer);

        $framework = $this->createMock(ContaoFramework::class);

        $controller = $this->getMockBuilder(RedirectShortUrlController::class)
            ->onlyMethods(['redirectToRoute'])
            ->getMock();

        $controller->expects(self::once())
            ->method('redirectToRoute')
            ->with('cms', ['to' => 'offer_list', 'auto_item' => $uuid->toBase58().'-some-alias'], Response::HTTP_MOVED_PERMANENTLY)
            ->willReturn($this->createMock(\Symfony\Component\HttpFoundation\RedirectResponse::class));

        $controller->__invoke(123, $repository, $framework);
    }
}
