<?php

namespace apexl\Io\modules\user\controllers;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\factories\RequestHelperFactory;
use apexl\Io\includes\Controller;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\user\Actions\ForgotPasswordAction;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\RequestHelper\ForgotPasswordRequestHelper;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class ForgotPasswordController extends Controller
{
    public function __invoke(
        ForgotPasswordAction $forgotPasswordAction,
        RequestHelperFactory $requestHelperFactory,
        RouteManager $routeManager,
        ServerRequestInterface $request,
        ResponseInterface $response
    ): ResponseInterface {
        $requestHelper = $requestHelperFactory->make(ForgotPasswordRequestHelper::class, $request);

        try {
            $user = userEntity::from('email', $requestHelper->email());

            $forgotPasswordAction->handle($user);

            $this->output->addMetadata(
                'user.forgot-password.redirect',
                'redirect',
                $routeManager->getRoutePattern('user.display.forgot-password.check-email')
            );
        } catch (RecordNotFoundException) {
            $this->output->addMessage('user.forgot-password', 'error', 'User account does not exist');
        }

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