<?php

namespace App\Service\Frontend;

use Symfony\Component\HttpFoundation\ResponseHeaderBag;

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

use Doctrine\ORM\EntityManagerInterface;

use App\Entity\User;
use App\Entity\UserDownloader;
use App\Entity\AnonymeDownloader;

class DownloadService
{
    public function __construct(
        private EntityManagerInterface $em,
        private UrlGeneratorInterface $urlGenerator
    ) {}

    public function downloadUser(int $id, string $name, string $filePath): BinaryFileResponse
    {
        $safeFilename = preg_replace('/[^\w.\-]/u', '_', $name) ?? $id . '.mp4';

        $response = new BinaryFileResponse($filePath);
        $response->setContentDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            $safeFilename
        );

        // 5. MIME type depuis l'extension stockée
        $mimeMap = [
            'mp4'  => 'video/mp4',
            'webm' => 'video/webm',
            'mkv'  => 'video/x-matroska',
            'avi'  => 'video/x-msvideo',
            'mov'  => 'video/quicktime',
            'flv'  => 'video/x-flv',
            'mp3'  => 'audio/mpeg',
            'm4a'  => 'audio/mp4',
        ];
        $ext  = pathinfo($name, PATHINFO_EXTENSION);
        $mime = $mimeMap[$ext] ?? 'application/octet-stream';
        $response->headers->set('Content-Type', $mime);

        // 6. Taille exacte pour la barre de progression du navigateur
        $response->headers->set('Content-Length', (string) filesize($filePath));

        // 7. Support des téléchargements partiels (resume)
        $response->headers->set('Accept-Ranges', 'bytes');

        // 8. Pas de mise en cache (fichier privé)
        $response->setPrivate();
        $response->setMaxAge(0);
        $response->headers->addCacheControlDirective('no-store');

        return $response;
    }


    public function downloadSaveStream(string $url, string $fileName, string $name, string $pathDownload, User $user = null): string
    {
        $pathDownload = $pathDownload . $fileName;
        $tailleOctets = filesize($pathDownload);
        $tailleMo = round($tailleOctets / (1024 * 1024),2);
        
        if ($user) {
            $userDownloader = new UserDownloader();
            $userDownloader->setNameFile($fileName);
            $userDownloader->setName($name);
            $userDownloader->setUrl($url);
            $userDownloader->setUser($user);
            $userDownloader->setDateAdd(new \DateTime());
            $userDownloader->setSizeFile($tailleMo);
            $userDownloader->setIsDelete(false);
            $this->em->persist($userDownloader);
            $this->em->flush();
            return $this->urlGenerator->generate('app_frontend_download_user', ['id' => $userDownloader->getId()]);
        } else {
            $anonymeDownloader = new AnonymeDownloader();
            $anonymeDownloader->setNameFile($fileName);
            $anonymeDownloader->setName($name);
            $anonymeDownloader->setUrl($url);
            $anonymeDownloader->setDateAdd(new \DateTime());
            $anonymeDownloader->setSizeFile($tailleMo);
            $this->em->persist($anonymeDownloader);
            $this->em->flush();
            return $this->urlGenerator->generate('app_frontend_download_anonyme', ['id' => $anonymeDownloader->getId()]);
        }
    }
}
