<?php

namespace App\Service;

use App\Entity\AnalyticsEvent;
use App\Entity\AnalyticsUniqId;
use Doctrine\ORM\EntityManagerInterface;
use Dompdf\Dompdf;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Twig\Environment;

/**
 * @codeCoverageIgnore RGPD data access/deletion with PDF generation
 */
class RgpdService
{
    public function __construct(
        private EntityManagerInterface $em,
        private Environment $twig,
        private MailerService $mailer,
        #[Autowire('%kernel.project_dir%')] private string $projectDir,
    ) {
    }

    /**
     * @return array{found: bool, count: int}
     */
    public function handleAccessRequest(string $ip, string $email): array
    {
        $ipHash = hash('sha256', $ip);
        $visitors = $this->em->getRepository(AnalyticsUniqId::class)->findBy(['ipHash' => $ipHash]);

        if (0 === \count($visitors)) {
            $this->mailer->sendEmail(
                $email,
                'E-Ticket - Demande d\'acces aux donnees (RGPD)',
                $this->twig->render('emails/rgpd_no_data.html.twig'),
                null,
                null,
                false,
            );

            return ['found' => false, 'count' => 0];
        }

        $data = [];
        foreach ($visitors as $visitor) {
            $events = $this->em->getRepository(AnalyticsEvent::class)->findBy(
                ['visitor' => $visitor],
                ['createdAt' => 'DESC'],
            );

            $data[] = [
                'visitor' => $visitor,
                'events' => $events,
            ];
        }

        $pdfPath = $this->generateAccessPdf($data, $ip);

        $this->mailer->sendEmail(
            $email,
            'E-Ticket - Vos donnees personnelles (RGPD)',
            $this->twig->render('emails/rgpd_access.html.twig'),
            null,
            null,
            false,
            [['path' => $pdfPath, 'name' => 'donnees-personnelles.pdf']],
        );

        @unlink($pdfPath);

        return ['found' => true, 'count' => \count($visitors)];
    }

    /**
     * @return array{found: bool, deleted: int}
     */
    public function handleDeletionRequest(string $ip, string $email): array
    {
        $ipHash = hash('sha256', $ip);
        $visitors = $this->em->getRepository(AnalyticsUniqId::class)->findBy(['ipHash' => $ipHash]);

        if (0 === \count($visitors)) {
            $this->mailer->sendEmail(
                $email,
                'E-Ticket - Demande de suppression (RGPD)',
                $this->twig->render('emails/rgpd_no_data.html.twig'),
                null,
                null,
                false,
            );

            return ['found' => false, 'deleted' => 0];
        }

        $count = \count($visitors);

        foreach ($visitors as $visitor) {
            $this->em->remove($visitor);
        }
        $this->em->flush();

        $pdfPath = $this->generateDeletionPdf($ip);

        $this->mailer->sendEmail(
            $email,
            'E-Ticket - Attestation de suppression (RGPD)',
            $this->twig->render('emails/rgpd_deletion.html.twig'),
            null,
            null,
            false,
            [['path' => $pdfPath, 'name' => 'attestation-suppression.pdf']],
        );

        @unlink($pdfPath);

        return ['found' => true, 'deleted' => $count];
    }

    /**
     * @param list<array{visitor: AnalyticsUniqId, events: list<AnalyticsEvent>}> $data
     */
    private function generateAccessPdf(array $data, string $ip): string
    {
        $logoPath = $this->projectDir.'/public/logo.png';
        $logoBase64 = file_exists($logoPath) ? 'data:image/png;base64,'.base64_encode((string) file_get_contents($logoPath)) : '';

        $html = $this->twig->render('pdf/rgpd_access.html.twig', [
            'data' => $data,
            'ip' => $ip,
            'logo' => $logoBase64,
            'date' => new \DateTimeImmutable(),
        ]);

        return $this->renderPdf($html);
    }

    private function generateDeletionPdf(string $ip): string
    {
        $logoPath = $this->projectDir.'/public/logo.png';
        $logoBase64 = file_exists($logoPath) ? 'data:image/png;base64,'.base64_encode((string) file_get_contents($logoPath)) : '';

        $html = $this->twig->render('pdf/rgpd_deletion.html.twig', [
            'ip' => $ip,
            'logo' => $logoBase64,
            'date' => new \DateTimeImmutable(),
        ]);

        return $this->renderPdf($html);
    }

    private function renderPdf(string $html): string
    {
        $dompdf = new Dompdf();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4');
        $dompdf->render();

        $path = tempnam(sys_get_temp_dir(), 'rgpd_').'.pdf';
        file_put_contents($path, $dompdf->output());

        return $path;
    }
}
