<?php

namespace App\Tests\Controller;

use App\Entity\OrganizerInvitation;
use App\Service\MailerService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class UnsubscribeControllerTest extends WebTestCase
{
    public function testInvalidTokenReturns404(): void
    {
        $client = static::createClient();
        $client->request('GET', '/unsubscribe/invalid-base64');

        self::assertResponseStatusCodeSame(404);
    }

    public function testValidTokenShowsUnsubscribePage(): void
    {
        $client = static::createClient();
        $token = base64_encode('user@example.com');
        $client->request('GET', '/unsubscribe/'.$token);

        self::assertResponseIsSuccessful();
    }

    public function testPostConfirmsUnsubscribe(): void
    {
        $client = static::createClient();
        $token = base64_encode('user@example.com');
        $client->request('POST', '/unsubscribe/'.$token);

        self::assertResponseIsSuccessful();
    }

    public function testPostRefusesInvitationsAndNotifiesAdmin(): void
    {
        $client = static::createClient();
        $em = static::getContainer()->get(EntityManagerInterface::class);

        $email = 'unsub-invite-'.uniqid().'@example.com';

        $invitation = new OrganizerInvitation();
        $invitation->setCompanyName('Asso Unsub');
        $invitation->setFirstName('Test');
        $invitation->setLastName('Unsub');
        $invitation->setEmail($email);
        $invitation->setStatus(OrganizerInvitation::STATUS_SENT);
        $em->persist($invitation);
        $em->flush();

        $mailer = $this->createMock(MailerService::class);
        $mailer->expects(self::once())->method('sendEmail')->with(
            $this->anything(),
            $this->stringContains('Desinscription'),
            $this->stringContains($email),
            null,
            null,
            false,
        );
        static::getContainer()->set(MailerService::class, $mailer);

        $token = base64_encode($email);
        $client->request('POST', '/unsubscribe/'.$token);

        self::assertResponseIsSuccessful();

        $freshEm = static::getContainer()->get(EntityManagerInterface::class);
        $updated = $freshEm->getRepository(OrganizerInvitation::class)->find($invitation->getId());
        self::assertSame(OrganizerInvitation::STATUS_REFUSED, $updated->getStatus());
        self::assertNotNull($updated->getRespondedAt());
    }
}
