<?php

namespace App\Controller\Admin;

use App\Module\Core\Service\ModuleActivator;
use App\Module\Core\Service\ModuleRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class ModuleController extends AbstractController
{
    public function __construct(
        private readonly ModuleRegistry $moduleRegistry,
        private readonly ModuleActivator $moduleActivator,
    ) {}

    #[Route('/modules', name: 'admin_modules')]
    public function index(): Response
    {
        $modules = $this->moduleRegistry->getAllModules();
        $moduleData = [];

        foreach ($modules as $slug => $module) {
            $moduleData[] = [
                'slug' => $slug,
                'name' => $module::getModuleName(),
                'description' => $module::getModuleDescription(),
                'version' => $module::getModuleVersion(),
                'isCore' => $module::isCore(),
                'isActive' => $this->moduleRegistry->isModuleActive($slug),
                'requiredPlan' => $module::getRequiredPlan(),
                'dependencies' => $module::getDependencies(),
            ];
        }

        return $this->render('admin/module/index.html.twig', [
            'modules' => $moduleData,
        ]);
    }

    #[Route('/modules/{slug}/toggle', name: 'admin_module_toggle', methods: ['POST'])]
    public function toggle(string $slug, Request $request): Response
    {
        if (!$this->isCsrfTokenValid('module_toggle_' . $slug, $request->request->get('_token'))) {
            $this->addFlash('error', 'Geçersiz CSRF token.');
            return $this->redirectToRoute('admin_modules');
        }

        try {
            if ($this->moduleRegistry->isModuleActive($slug)) {
                $this->moduleActivator->deactivate($slug);
                $this->addFlash('success', 'Modül devre dışı bırakıldı.');
            } else {
                $this->moduleActivator->activate($slug);
                $this->addFlash('success', 'Modül etkinleştirildi.');
            }
        } catch (\Exception $e) {
            $this->addFlash('error', $e->getMessage());
        }

        return $this->redirectToRoute('admin_modules');
    }
}
