<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\controllers\twoFactorAuth;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\includes\Controller;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\services\CurrentUserFactory;
use apexl\Io\modules\user\services\twoFactorAuth\TwoFactorAuthService;
use JsonException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * POST /api/v1/user/action/admin/users/{id}/two-factor-auth/reset
 *
 * Admin-assisted reset (Plan 007 §4): deactivates a target user's 2FA methods +
 * recovery codes and clears their flags, forcing re-enrolment on next login.
 * The backstop for a locked-out user in enforced mode. Guarded by the dedicated
 * User::RESET_TWO_FACTOR permission (not blanket MANAGE).
 */
final readonly class ResetTwoFactorController extends Controller
{
    /**
     * @throws JsonException
     */
    public function __invoke(
        ServerRequestInterface $request,
        ResponseInterface $response,
        CurrentUserFactory $currentUserFactory,
        TwoFactorAuthService $twoFactorService,
        int $id,
    ): ResponseInterface {
        try {
            $target = userEntity::fromPrimaryKey($id);
        } catch (RecordNotFoundException) {
            return $this->json($response, ['error' => 'User not found'], 404);
        }

        $actor = $currentUserFactory->get();
        $twoFactorService->reset($target, $actor?->id ? (int) $actor->id : null);

        $this->output->addResponse($request, [
            'two_factor_reset' => true,
            'user_id' => (int) $target->id,
        ]);

        return $this->json($response);
    }
}
