<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\Actions;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\includes\HookManager;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\exceptions\LoginException;
use apexl\Io\modules\user\interfaces\UserPasswordVerifierInterface;

final readonly class ValidateLoginAction
{
    public final const string HOOK__POST_AUTH = 'login.post_auth';

    public function __construct(
        private HookManager $hookManager,
        private UserPasswordVerifierInterface $userPasswordVerifier
    ) {}

    /**
     * @throws LoginException
     */
    public function handle(string $username, string $password): ?userEntity
    {
        try {
            $user = userEntity::from('email', $username);
        } catch (RecordNotFoundException) {
            throw new LoginException('Unknown user', 401);
        }
        //if we have user data, grab the salt and password and check the provided one matches.
        //we also need the user to be active, so check that at the same time.
        if ($user->active === true) {
            $verified = $this->userPasswordVerifier->verify($password, $user->password);
            $verified = $this->hookManager->processHook(self::HOOK__POST_AUTH, $verified, $user);

            if ($verified === true) {
                return $user;
            }
        }

        throw new LoginException('The email address and password don\'t match', 401);
    }
}