<?php

declare(strict_types=1);

namespace BotGuard\Controllers\Web;

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\Services\VerificationService;

/**
 * Serves the public verification experience: the landing page that runs the
 * security checks and challenge, plus the terminal "success" and "blocked"
 * pages a session can be routed to.
 */
final class VerifyController extends Controller
{
    public function __construct(
        View $view,
        Session $session,
        Csrf $csrf,
        Request $request,
        private VerificationService $verification,
    ) {
        parent::__construct($view, $session, $csrf, $request);
    }

    /**
     * Render the verification page and issue a fresh challenge/session.
     */
    public function show(Request $request): Response
    {
        $issued = $this->verification->createSession($request);

        $response = $this->render('web.verify', [
            'title'      => 'Security Verification',
            'token'      => $issued['token'],
            'challenge'  => $issued['challenge'],
            'provider'   => $issued['provider'],
            'issuedAtMs' => $issued['issued_at_ms'],
        ]);

        // Non-HttpOnly probe cookie so the client can prove cookie persistence.
        return $response->withCookie('bg_probe', $issued['token'], [
            'expires'  => time() + 900,
            'path'     => '/',
            'httponly' => false,
            'samesite' => 'Lax',
        ]);
    }

    /**
     * Informational page shown when a session is blocked.
     */
    public function blocked(Request $request): Response
    {
        return $this->render('web.blocked', ['title' => 'Access Blocked']);
    }

    /**
     * Fallback success page (used when no primary URL is configured).
     */
    public function success(Request $request): Response
    {
        return $this->render('web.success', ['title' => 'Verified']);
    }
}
