<?php

namespace Velis\Mvc\Authentication\Strategy;

use Application\Facade\MagicLinks;
use Velis\App;
use Velis\Exception\TokenExpiredException;
use Exception;
use Phalcon\Http\RequestInterface;
use Velis\Arrays;
use Velis\Debug;
use Velis\Exception\UnauthorizedException;
use Velis\Mvc\Authentication\Strategy\TokenStrategyInterface;
use Velis\Timezone;

class MagicTokenStrategy implements TokenStrategyInterface
{
    private string $authMethod = 'token';

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

    /**
     * @throws TokenExpiredException
     * @throws UnauthorizedException
     */
    public function canPass(RequestInterface $request): bool
    {
        $token = $request->authorization();
        $magicLink = MagicLinks::getByToken($token);
        if (!$magicLink || $magicLink->isExpired()) {
            throw new TokenExpiredException();
        }

        $uri = $request->getURI();
        if (!Arrays::find($magicLink->relationAllowedPaths()->get(), 'path', $uri)) {
            throw new UnauthorizedException();
        }

        MagicLinks::auth($token);

        return true;
    }
}
