<?php

namespace App\Controller;

use App\Entity\Mod;
use App\Entity\Modpack;
use App\Form\Modpack\ModpackDownloadType;
use App\Service\ModpackZipService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/modpacks')]
final class ModpackController extends AbstractController
{
    #[Route('', name: 'app_modpack')]
    public function index(Request $request, EntityManagerInterface $em): Response
    {
        $modpacks = $em->getRepository(Modpack::class)->findBy(
            ['downloadable' => true],
            ['version' => 'DESC']
        );

        $id = $request->query->get('v');
        $modpack = $id
            ? $em->getRepository(Modpack::class)->find($id)
            : ($modpacks[0] ?? null);

        // Sécurité : le modpack demandé doit être downloadable
        if (!$modpack || !$modpack->isDownloadable()) {
            $modpack = $modpacks[0] ?? null;
        }

        // Si aucun modpack n'est disponible, afficher le template approprié
        if (!$modpack) {
            return $this->render('modpack/nomodpack.html.twig');
        }

        $form = $this->createForm(ModpackDownloadType::class, $modpack);

        return $this->render('modpack/index.html.twig', [
            'modpack'  => $modpack,
            'modpacks' => $modpacks,
            'form'     => $form,
        ]);
    }

    #[Route('/{id}/download', name: 'app_modpack_download')]
    public function download(
        Modpack $modpack,
        Request $request,
        EntityManagerInterface $em,
        ModpackZipService $modpackZipService
    ): Response {
        // Mods obligatoires
        $mods = $modpack->getConstitues()
            ->filter(fn($c) => !$c->isOptionnel())
            ->map(fn($c) => $c->getMod())
            ->getValues();

        // Mods optionnels depuis ?opt=1+2+3
        $optParam = $request->query->get('opt', '');
        $optIds   = array_filter(explode(' ', $optParam)); // "+" décodé en espace par PHP

        if (!empty($optIds)) {
            // Sécurité : on vérifie que les IDs appartiennent bien au modpack
            $allowedOptIds = $modpack->getConstitues()
                ->filter(fn($c) => $c->isOptionnel())
                ->map(fn($c) => (string) $c->getMod()->getId())
                ->getValues();

            $safeIds        = array_intersect($optIds, $allowedOptIds);
            $modsOptionnels = $em->getRepository(Mod::class)->findBy(['id' => $safeIds]);
            $mods           = array_merge($mods, $modsOptionnels);
        }

        $zipPath = $modpackZipService->createZip($modpack, $mods);

        $response = new BinaryFileResponse($zipPath);
        $response->setContentDisposition(
            ResponseHeaderBag::DISPOSITION_ATTACHMENT,
            'modpack-' . $modpack->getVersion() . '.zip'
        );
        $response->deleteFileAfterSend(true);

        return $response;
    }
}
