<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Account;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use PragmaRX\Google2FA\Google2FA;

final class EnableMfaController
{
    private const string SESSION_PENDING_SECRET = 'mfa_pending_secret';

    public function __invoke(Request $request): JsonResponse
    {
        $user = $request->user();
        assert($user !== null);
        $google2fa = new Google2FA;

        $secret = $google2fa->generateSecretKey();

        $request->session()->put(self::SESSION_PENDING_SECRET, $secret);

        $qrCodeUrl = $google2fa->getQRCodeUrl(
            config('app.name', 'Builder'),
            (string) $user->getAttribute('email'),
            $secret,
        );

        return response()->json([
            'secret' => $secret,
            'qr_code_url' => $qrCodeUrl,
        ]);
    }
}
