<?php

namespace App\Tests\Controller;

use App\Entity\EmailTracking;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class EmailTrackingControllerTest extends WebTestCase
{
    private function ensureLogoExists(): void
    {
        $projectDir = static::getContainer()->getParameter('kernel.project_dir');
        $logoPath = $projectDir.'/public/logo.jpg';

        if (!file_exists($logoPath)) {
            file_put_contents($logoPath, 'fake-image');
        }
    }

    public function testTrackReturnsImageResponse(): void
    {
        $client = static::createClient();
        $this->ensureLogoExists();

        $client->request('GET', '/track/nonexistent-id/logo.jpg');

        self::assertResponseIsSuccessful();
    }

    public function testTrackMarksAsOpened(): void
    {
        $client = static::createClient();
        $this->ensureLogoExists();

        $em = static::getContainer()->get(EntityManagerInterface::class);
        $tracking = new EmailTracking('test-track-'.uniqid(), 'user@example.com', 'Test Subject');
        $em->persist($tracking);
        $em->flush();

        $client->request('GET', '/track/'.$tracking->getMessageId().'/logo.jpg');

        self::assertResponseIsSuccessful();

        $em->refresh($tracking);
        self::assertSame('opened', $tracking->getState());
        self::assertNotNull($tracking->getOpenedAt());
    }
}
