<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Account;

use Builder\Core\Extensions\Account\AccountProfile;
use Builder\Core\Foundation\Account\AccountDefinition;
use Builder\Core\Foundation\Registry;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

final class ShowAccountController
{
    public function __construct(private readonly Registry $registry) {}

    public function __invoke(Request $request): Response
    {
        $user = $request->user();
        assert($user !== null);
        $definition = $this->makeDefinition();

        return Inertia::render('Account/Index', [
            'accountDefinition' => $definition->toArray(),
            'user' => $user,
            'mfaEnabled' => $user->getAttribute('two_factor_confirmed_at') !== null,
            'recoveryCodes' => $user->getAttribute('two_factor_confirmed_at') !== null && $request->session()->get('show_recovery_codes')
                ? json_decode((string) decrypt((string) $user->getAttribute('two_factor_recovery_codes')), true)
                : null,
        ]);
    }

    private function makeDefinition(): AccountDefinition
    {
        return AccountDefinition::make(new AccountProfile, $this->registry->accountExtensions());
    }
}
