<?php

namespace apexl\Io\modules\user\controllers;

use apexl\Io\exceptions\RecordNotFoundException;
use apexl\Io\includes\Controller;
use apexl\Io\modules\user\Actions\ForgotPasswordWithLinkAction;
use apexl\Io\modules\user\exceptions\ForgotPasswordLinkExpiredException;
use apexl\Io\modules\user\Factories\ForgotPasswordLinkFactory;
use apexl\Io\services\HttpPaths;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class ForgotPasswordWithLinkController extends Controller
{
    public function __invoke(
        ForgotPasswordWithLinkAction $forgotPasswordWithLinkAction,
        ForgotPasswordLinkFactory $forgotPasswordLinkService,
        HttpPaths $path,
        ServerRequestInterface $request,
        ResponseInterface $response,
        string $hash,
    ): ResponseInterface {
        try {
            [$authToken, $refreshToken] = $forgotPasswordWithLinkAction->handle($hash);

            $this->output->addResponse($request, [
                'access_token' => $authToken,
                'refresh_token' => $refreshToken,
            ]);

            return $this->json($response);
        } catch (RecordNotFoundException|ForgotPasswordLinkExpiredException) {
            $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);
        }
    }
}
