<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Actions;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\exceptions\ForgotPasswordLinkExpiredException;
use apexl\Io\modules\user\services\ForgotPasswordLinkService;

final readonly class ForgotPasswordWithLinkAction
{
    public function __construct(
        private ForgotPasswordLinkService $forgotPasswordLinkService,
        private StartLoggedInSession $startLoggedInSession,
    ) {}

    /**
     * @throws RecordNotFoundException
     * @throws ForgotPasswordLinkExpiredException
     */
    public function handle(string $hash): array
    {
        $forgotPassword = $this->forgotPasswordLinkService->get($hash);

        if ($forgotPassword->isExpired() || $forgotPassword->used) {
            throw new ForgotPasswordLinkExpiredException();
        }

        $forgotPassword->markUsed();

        $user = userEntity::fromEmail($forgotPassword->email);

        return $this->startLoggedInSession->handle($user);
    }
}