<?php

namespace apexl\Io\modules\user\controllers;

use apexl\hashing\Hash;
use apexl\Io\includes\Controller;
use apexl\Io\includes\RouteManager;
use apexl\Io\modules\user\entities\userEntity;
use apexl\Io\services\HttpPaths;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class ResetPasswordController extends Controller
{
    /**
     * @throws Exception
     */
    public function __invoke(
        HttpPaths $path,
        RouteManager $routeManager,
        ServerRequestInterface $request,
        ResponseInterface $response
    ): ResponseInterface {
        $body = (object) $request->getParsedBody();
        if ($body->password != $body->confirm_password) {
            $this->output->addMessage(
                $path->getRouteName($request) . '.validation',
                'error',
                'Passwords don\'t match'
            );
            $this->output->addResponse($request, [], false); //added so we can hook into this elsewhere.
            return $this->json($response, [], 400);
        }


        $user = new userEntity();
        $match = $user->getForgottenPasswordLink($body->hash);
        if (!empty($match) && ((time() - $match['created']) <= 86400 && $match['used'] == 0)) {
            $user->markForgottenPasswordLinkUsed($body->hash);
            $user->getUserByEmail($match['email']);
            if (isset($user->id) && $user->id > 0 && isset($body->password) && !empty($body->password)) {

                $hash = new Hash();
                $hashData = $hash->hashString($body->password);
                $passwordHash = $hashData->hash;
                $passwordSalt = $hashData->salt;
                unset($body->password);

                $user->password = $passwordHash;
                $user->salt = $passwordSalt;
                $user->store();

                $this->output->addMetadata(
                    'user.login.validation.redirect',
                    'redirect',
                    $routeManager->getRoutePattern('user.display.reset-password-success')
                );
                return $this->json($response, ['success' => true]);
            }
        }

        $this->output->addMessage(
            $path->getRouteName($request) . '.validation',
            'error',
            'We were unable to reset your password'
        );
        return $this->json($response, [], 400);

    }
}
