<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Actions;

use apexl\hashing\Hash;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\services\ForgotPasswordEmailFactory;
use apexl\Io\modules\user\services\ForgotPasswordLinkService;

final readonly class ForgotPasswordAction
{
    public function __construct(
        private ForgotPasswordEmailFactory $forgotPasswordEmailFactory,
        private ForgotPasswordLinkService $forgotPasswordLinkService,
        private RouteManager $routeManager,
        private Hash $hash,
    ) {}

    public function handle(userEntity $user): void
    {
        //now we send email to the user.
        $this->forgotPasswordEmailFactory->create(
            $user->first_name,
            $user->email,
            $this->link($user),
        );
    }

    private function link(userEntity $user): string
    {
        //we do this so the has can be passed back as a url param rather than a query string.
        $randomHash = str_replace('/', '@', $this->hash->generateRandomHash());
        //write the hash to the database
        $this->forgotPasswordLinkService->create($user->email, $randomHash);

        return $this->routeManager->getRoutePattern('user.display.reset-password', ['hash' => $randomHash]);
    }
}