<?php

namespace App\Tests\Command;

use App\Command\TestMailCommand;
use App\Service\MailerService;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Tester\CommandTester;
use Twig\Environment;

class TestMailCommandTest extends TestCase
{
    public function testExecuteDev(): void
    {
        $mailer = $this->createStub(MailerService::class);
        $twig = $this->createStub(Environment::class);
        $twig->method('render')->willReturn('<html>test</html>');

        $command = new TestMailCommand($mailer, $twig);
        $tester = new CommandTester($command);
        $tester->execute(['email' => 'test@test.com']);

        $this->assertSame(0, $tester->getStatusCode());
        $this->assertStringContainsString('test@test.com', $tester->getDisplay());
        $this->assertStringContainsString('dev', $tester->getDisplay());
    }

    public function testExecuteProd(): void
    {
        $mailer = $this->createStub(MailerService::class);
        $twig = $this->createStub(Environment::class);
        $twig->method('render')->willReturn('<html>prod test</html>');

        $command = new TestMailCommand($mailer, $twig);
        $tester = new CommandTester($command);
        $tester->execute(['email' => 'prod@test.com', '--mode' => 'prod']);

        $this->assertSame(0, $tester->getStatusCode());
        $this->assertStringContainsString('prod@test.com', $tester->getDisplay());
        $this->assertStringContainsString('prod', $tester->getDisplay());
    }

    public function testForceDsnFailureReturnsFailure(): void
    {
        $mailer = $this->createStub(MailerService::class);
        $twig = $this->createStub(Environment::class);
        $twig->method('render')->willReturn('<html>test</html>');

        $command = new TestMailCommand($mailer, $twig);
        $tester = new CommandTester($command);

        // An invalid DSN will throw an exception inside sendViaForceDsn -> returns FAILURE
        $tester->execute([
            'email' => 'test@test.com',
            '--force-dsn' => 'invalid-dsn://this.will.fail',
        ]);

        $this->assertSame(1, $tester->getStatusCode());
        $this->assertStringContainsString('Echec envoi via force-dsn', $tester->getDisplay());
    }

    public function testForceDsnSuccessReturnsSuccess(): void
    {
        $mailer = $this->createStub(MailerService::class);
        $twig = $this->createStub(Environment::class);
        $twig->method('render')->willReturn('<html>test</html>');

        $command = new TestMailCommand($mailer, $twig);
        $tester = new CommandTester($command);

        // Use the null transport DSN which succeeds without a real SMTP server
        $tester->execute([
            'email' => 'test@test.com',
            '--force-dsn' => 'null://null',
        ]);

        $this->assertSame(0, $tester->getStatusCode());
        $this->assertStringContainsString('test@test.com', $tester->getDisplay());
    }
}
