<?php

namespace App\Tests\Service\Mailer;

use App\Service\Mailer\Mailer;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\Profiler\Profiler;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Twig\Environment;

class MailerTest extends TestCase
{
    public function testSend(): void
    {
        $symfonyMailer = $this->createMock(MailerInterface::class);
        $entityManager = $this->createStub(EntityManagerInterface::class);
        $urlGenerator = $this->createStub(UrlGeneratorInterface::class);
        $profiler = $this->createStub(Profiler::class);
        $twig = $this->createMock(Environment::class);

        $mailer = new Mailer(
            $symfonyMailer,
            $entityManager,
            $urlGenerator,
            $profiler,
            $twig
        );

        $template = 'mails/test.twig';
        $data = ['foo' => 'bar'];

        // Mock Twig rendering
        // 1. First call for MJML content
        // 2. Second call for Text content (fallback)
        $twig->expects($this->exactly(2))
            ->method('render')
            ->willReturnCallback(function ($tpl, $ctx) use ($template) {
                if ($tpl === $template) {
                    return '<mjml><mj-body>Hello</mj-body></mjml>';
                }
                if ($tpl === 'txt-' . $template) {
                    return 'Hello Text';
                }
                return '';
            });

        $symfonyMailer->expects($this->once())
            ->method('send')
            ->with($this->isInstanceOf(Email::class));

        $mailer->send(
            'dest@example.com',
            'Dest Name',
            'Subject',
            $template,
            $data
        );
    }
}
