<?php

namespace Velis\Mvc\Controller;

use Application\Facade\MagicLinks;
use Exception;
use Phalcon\Events\Event;
use Phalcon\Http\RequestInterface;
use Phalcon\Mvc\Dispatcher;
use Throwable;
use Velis\Api\HttpExceptionHandler\HttpException;
use Velis\App;
use Velis\Debug;
use Velis\Exception\TokenExpiredException;
use Velis\Exception\UnauthorizedException;
use Velis\Lang;
use Velis\Mvc\Authentication\Strategy\ApiTokenStrategy;
use Velis\Mvc\Authentication\Strategy\MagicTokenStrategy;
use Velis\Mvc\Authentication\Strategy\TokenStrategyInterface;
use Velis\Mvc\Controller\RestRequestHandler\AbstractRestRequestHandler;

/**
 * This middleware is responsible for authenticating the user using a cookie.
 * It would be useful, when the user is already logged via cookie&session, and we want to authenticate him
 * in the API that uses Authentication Token.
 * In simple words, it would be useful when we want to authenticate the user in the API using the cookie.
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
class AuthenticationChecker
{
    private TokenStrategyInterface $tokenStrategy;

    public function __construct(protected Dispatcher $dispatcher)
    {
    }

    /**
     * @throws TokenExpiredException
     * @throws UnauthorizedException
     */
    public function handle(): void
    {
        /** @var RequestInterface $request */
        $request = $this->dispatcher->getDI()->get('request');

        if (MagicLinks::isMagicRequest($request)) {
            $this->tokenStrategy = new MagicTokenStrategy();
        } else {
            $this->tokenStrategy = new ApiTokenStrategy();
        }

        if (!$this->tokenStrategy->canPass($request)) {
            throw new UnauthorizedException();
        }

        App::$registry['authMethod'] = $this->tokenStrategy->getAuthMethod();
    }

    public function getAuthMethod(): string
    {
        return $this->tokenStrategy->getAuthMethod();
    }
}
