<?php

declare(strict_types=1);

namespace apexl\Io\modules\userDisplay\controllers;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\display\components\BasicLink;
use apexl\Io\modules\display\components\ContentTitle;
use apexl\Io\modules\display\Controllers\DisplayController;
use apexl\Io\modules\user\entities\PasswordReset;
use apexl\Io\modules\user\exceptions\ForgotPasswordLinkExpiredException;
use apexl\Io\modules\userDisplay\FormBuilders\ResetPasswordFormBuilder;
use apexl\Io\services\VariableManager;
use JsonException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class ResetPasswordDisplayController extends DisplayController
{
    /**
     * @throws JsonException
     */
    public function __invoke(
        ServerRequestInterface $request,
        ResponseInterface $response,
        ResetPasswordFormBuilder $formBuilder,
        RouteManager $routeManager,
        VariableManager $variableManager,
        string $hash
    ): ResponseInterface {
        $this->render->setActive("noUI");
        $this->render->setPageTitle("Reset Password");

        try {
            $match = PasswordReset::fromHash($hash);

            $this->output->addResponse($request, $this->render->build([
                $formBuilder->build(['hash' => $match->hash]),

                $this->component(BasicLink::class)
                    ->addClass('forgottenPasswordLink return mt-5 text-decoration-underline')
                    ->addRoute($routeManager->getRoutePattern('user.display.login'))
                    ->addText($variableManager->get('user_login_return_login_text') ?? 'Return to login'),
            ]));

        } catch (RecordNotFoundException|ForgotPasswordLinkExpiredException) {
            $this->output->addResponse($request, $this->render->build([
                $this->component(ContentTitle::class)
                    ->addTitle('Your reset link has expired')
                    ->addContent('Please request a new password reset link using the button below:')
                    ->addClass('mb-5'),

                $this->component(BasicLink::class)
                    ->addClass('btn btn-primary')
                    ->addText('Go to Password Reset')
                    ->addRoute($routeManager->getRoutePattern('user.display.forgot-password'))
            ]));
        }

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

}


