<?php

namespace App\Controller;

use App\Service\CbrToCbzConverter;
use App\Service\NotificationService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Annotation\Route;

class ConversionController extends AbstractController
{
    public function __construct(
        private readonly CbrToCbzConverter $cbrToCbzConverter,
        private readonly NotificationService $notificationService
    ) {
    }

    #[Route('/convert', name: 'app_convert')]
    public function convert(Request $request): Response
    {
        if ($request->isMethod('POST')) {
            /** @var UploadedFile $file */
            $file = $request->files->get('file');

            if ($file && $file->getClientOriginalExtension() === 'cbr') {
                $originalFileName = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                $tempFilePath = $file->getPathname();

                try {
                    $cbzPath = $this->cbrToCbzConverter->convert($tempFilePath);

                    $response = new BinaryFileResponse($cbzPath);
                    $response->setContentDisposition(
                        ResponseHeaderBag::DISPOSITION_ATTACHMENT,
                        $originalFileName . '.cbz'
                    );
                    $response->headers->set('Content-Type', 'application/x-cbz');
                    $response->headers->set('Turbo-Visit-Control', 'reload');

                    $response->deleteFileAfterSend(true);

                    return $response;
                } catch (\Exception $e) {
                    $this->notificationService->sendUpdate([
                        'status' => 'error',
                        'message' => 'Une erreur est survenue lors de la conversion : ' . $e->getMessage()
                    ]);
                }
            } else {
                $this->notificationService->sendUpdate([
                    'status' => 'error',
                    'message' => 'Veuillez sélectionner un fichier CBR valide.'
                ]);
            }
        }

        return $this->render('conversion/index.html.twig');
    }
}
