<?php

declare(strict_types=1);

namespace BotGuard\Controllers\Admin;

use BotGuard\Core\Auth;
use BotGuard\Core\Controller;
use BotGuard\Core\Csrf;
use BotGuard\Core\Request;
use BotGuard\Core\Response;
use BotGuard\Core\Session;
use BotGuard\Core\View;
use BotGuard\Models\AuditLog;
use BotGuard\Models\ModuleConfig;

/**
 * Admin screen to enable/disable detection modules and tune their weights.
 * Changes take effect immediately (the engine reads module_configs per request).
 */
final class ModuleController extends Controller
{
    public function __construct(
        View $view,
        Session $session,
        Csrf $csrf,
        Request $request,
        private ModuleConfig $modules,
        private AuditLog $audit,
        private Auth $auth,
    ) {
        parent::__construct($view, $session, $csrf, $request);
    }

    public function index(Request $request): Response
    {
        return $this->render('admin.modules', [
            'title'   => 'Detection Modules',
            'modules' => $this->modules->ordered(),
        ]);
    }

    public function update(Request $request): Response
    {
        // Expects arrays keyed by module_key: enabled[key]=1, weight[key]=n
        $enabled = (array) $request->input('enabled', []);
        $weights = (array) $request->input('weight', []);

        foreach ($this->modules->ordered() as $module) {
            $key = (string) $module['module_key'];
            $isEnabled = isset($enabled[$key]);
            $weight = (float) clamp((float) ($weights[$key] ?? $module['weight']), 0, 100);
            $this->modules->setEnabledAndWeight($key, $isEnabled, $weight);
        }

        $this->audit->record($this->auth->id(), 'modules.updated', $request->ip(), [
            'enabled' => array_keys($enabled),
        ]);

        return $this->redirect('/admin/modules', 'success', 'Module configuration saved.');
    }
}
