<?php

namespace apexl\Io\modules\user\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\modules\user\services\userTools;
use apexl\Io\services\HttpPaths;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class ForgotPasswordWithLinkController extends Controller
{
    public function __invoke(
        userTools $userTools,
        HttpPaths $path,
        ServerRequestInterface $request,
        ResponseInterface $response,
        ?string $hash,
    ): ResponseInterface {
        if ($hash) {
            $user = new userEntity();
            $match = $user->getForgottenPasswordLink($hash);
            if (!empty($match) && ((time() - $match['created']) <= 86400 && $match['used'] == 0)) {
                //log the user in and send them to their settings page to update the password. flag the hash as used.
                $user->markForgottenPasswordLinkUsed($hash);
                $user->getUserByEmail($match['email']);
                if ($user->id ?? false) {
                    //log the user in.
                    [$authToken] = $userTools->startLoggedInSession($user);
                    $this->output->addResponse($request, ['access_token' => $authToken]
                    ); //added so we can hook into this elsewhere.

                    return $this->json($response);
                }
            }
        }
        $this->output->addMessage(
            $path->getRouteName($request) . '.validation',
            'error',
            "Invalid, unknown or expired hash"
        );
        $this->output->addResponse($request, [], false); //added so we can hook into this elsewhere.

        return $this->json($response, [], 400);
    }
}
