<?php

namespace App\Controller;

use App\Repository\EmailTrackingRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class EmailTrackingController extends AbstractController
{
    #[Route('/track/{messageId}/logo.jpg', name: 'app_email_track', methods: ['GET'])]
    public function track(
        string $messageId,
        EmailTrackingRepository $repository,
        EntityManagerInterface $em,
        #[Autowire('%kernel.project_dir%')] string $projectDir,
    ): Response {
        $tracking = $repository->findOneBy(['messageId' => $messageId]);

        if (null !== $tracking) {
            $tracking->markAsOpened();
            $em->flush();
        }

        $response = new BinaryFileResponse($projectDir.'/public/logo.jpg');
        $response->headers->set('Content-Type', 'image/jpeg');
        $response->headers->set('Cache-Control', 'no-store');

        return $response;
    }
}
