<?php

declare(strict_types=1);

namespace BotGuard\Controllers\Auth;

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\RedirectConfig;
use BotGuard\Models\User;
use BotGuard\Services\Mail\Mailer;

/**
 * Self-service registration for dashboard (non-admin) users. Each new user gets
 * a default redirect configuration so their verification decisions resolve.
 */
final class RegisterController extends Controller
{
    public function __construct(
        View $view,
        Session $session,
        Csrf $csrf,
        Request $request,
        private Auth $auth,
        private User $users,
        private RedirectConfig $redirects,
        private Mailer $mailer,
    ) {
        parent::__construct($view, $session, $csrf, $request);
    }

    public function show(Request $request): Response
    {
        if ($this->auth->check()) {
            return Response::redirect('/dashboard');
        }

        return $this->render('auth.register', ['title' => 'Create account']);
    }

    public function register(Request $request): Response
    {
        $validator = $this->validate([
            'name'     => 'required|minlen:2|maxlen:120',
            'email'    => 'required|email',
            'password' => 'required|minlen:8|confirmed',
        ]);

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

        $email = strtolower((string) $request->input('email'));

        if ($this->users->findByEmail($email) !== null) {
            return $this->redirect('/register', 'error', 'That email is already registered.');
        }

        $userId = $this->users->create([
            'name'     => (string) $request->input('name'),
            'email'    => $email,
            'password' => Auth::hash((string) $request->input('password')),
            'role'     => 'user',
            'status'   => 'active',
            'api_key'  => str_random(32),
        ]);

        $base = rtrim((string) config('app.url'), '/');
        $this->redirects->create([
            'user_id'       => $userId,
            'name'          => 'Default',
            'primary_url'   => $base . '/success',
            'alternate_url' => $base . '/blocked',
            'block_message' => 'Automated traffic detected.',
            'is_default'    => 1,
        ]);

        $this->auth->login($userId);

        // Best-effort welcome email — never block registration on mail delivery.
        if ($this->mailer->isConfigured()) {
            $this->mailer->send($email, 'Welcome to ' . config('app.name', 'BotGuard'), 'welcome', [
                'name' => (string) $request->input('name'),
            ]);
        }

        return $this->redirect('/dashboard', 'success', 'Welcome! Your account is ready.');
    }
}
