<?php

declare(strict_types=1);

namespace Builder\Core\Http\Controllers\Account;

use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

final class RegenerateMfaCodesController
{
    public function __invoke(Request $request): RedirectResponse
    {
        $user = $request->user();
        assert($user !== null);

        if ($user->getAttribute('two_factor_confirmed_at') === null) {
            return back()->withErrors(['mfa' => 'MFA is not enabled.']);
        }

        $user->forceFill([
            'two_factor_recovery_codes' => encrypt(json_encode($this->generateRecoveryCodes())),
        ])->save();

        $request->session()->put('show_recovery_codes', true);

        return to_route('builder.account.show')->with('success', __('builder::builder.account.recovery_codes_regenerated'));
    }

    /** @return list<string> */
    private function generateRecoveryCodes(): array
    {
        return array_map(
            fn () => strtoupper(bin2hex(random_bytes(4))).'-'.strtoupper(bin2hex(random_bytes(4))),
            range(1, 8),
        );
    }
}
