<?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\Threshold;

/**
 * Admin screen to configure the score bands (Human/Suspicious minimums) and the
 * action taken for each classification.
 */
final class ThresholdController extends Controller
{
    private const ACTIONS = ['redirect_primary', 'redirect_alternate', 'block', 'allow'];

    public function __construct(
        View $view,
        Session $session,
        Csrf $csrf,
        Request $request,
        private Threshold $thresholds,
        private AuditLog $audit,
        private Auth $auth,
    ) {
        parent::__construct($view, $session, $csrf, $request);
    }

    public function index(Request $request): Response
    {
        return $this->render('admin.thresholds', [
            'title'      => 'Risk Thresholds',
            'thresholds' => $this->thresholds->map(),
            'actions'    => self::ACTIONS,
        ]);
    }

    public function update(Request $request): Response
    {
        $humanMin = (int) clamp((float) $request->input('human_min', 80), 0, 100);
        $suspiciousMin = (int) clamp((float) $request->input('suspicious_min', 60), 0, 100);

        if ($suspiciousMin >= $humanMin) {
            return $this->redirect('/admin/thresholds', 'error', 'Suspicious minimum must be below the Human minimum.');
        }

        $this->thresholds->updateBand('human', $humanMin, $this->action($request->input('human_action')));
        $this->thresholds->updateBand('suspicious', $suspiciousMin, $this->action($request->input('suspicious_action')));
        $this->thresholds->updateBand('bot', 0, $this->action($request->input('bot_action'), 'block'));

        $this->audit->record($this->auth->id(), 'thresholds.updated', $request->ip(), [
            'human_min' => $humanMin, 'suspicious_min' => $suspiciousMin,
        ]);

        return $this->redirect('/admin/thresholds', 'success', 'Thresholds updated.');
    }

    private function action(mixed $value, string $default = 'redirect_alternate'): string
    {
        $value = (string) $value;

        return in_array($value, self::ACTIONS, true) ? $value : $default;
    }
}
