<?php

declare(strict_types=1);

namespace BotGuard\Controllers\User;

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\RedirectConfig;

/**
 * Lets a user configure where verified humans (primary URL) and high-risk
 * sessions (alternate URL / block message) are sent.
 */
final class RedirectConfigController extends Controller
{
    public function __construct(
        View $view,
        Session $session,
        Csrf $csrf,
        Request $request,
        private Auth $auth,
        private RedirectConfig $redirects,
        private AuditLog $audit,
    ) {
        parent::__construct($view, $session, $csrf, $request);
    }

    public function edit(Request $request): Response
    {
        $userId = (int) $this->auth->id();
        $config = $this->redirects->defaultForUser($userId);

        return $this->render('user.redirects', [
            'title'  => 'Redirect Configuration',
            'config' => $config,
        ]);
    }

    public function update(Request $request): Response
    {
        $validator = $this->validate([
            'primary_url'   => 'required|url|maxlen:2048',
            'alternate_url' => 'url|maxlen:2048',
        ]);

        if ($validator->fails()) {
            return $this->redirect('/dashboard/redirects', 'error', $validator->firstError());
        }

        $userId = (int) $this->auth->id();
        $config = $this->redirects->defaultForUser($userId);

        $data = [
            'primary_url'   => (string) $request->input('primary_url'),
            'alternate_url' => (string) $request->input('alternate_url'),
            'block_message' => mb_substr((string) $request->input('block_message', ''), 0, 500),
        ];

        if ($config === null) {
            $data['user_id'] = $userId;
            $data['name'] = 'Default';
            $data['is_default'] = 1;
            $this->redirects->create($data);
        } else {
            $this->redirects->updateById((int) $config['id'], $data);
        }

        $this->audit->record($userId, 'redirects.updated', $request->ip(), $data);

        return $this->redirect('/dashboard/redirects', 'success', 'Redirect configuration saved.');
    }
}
