<?php
namespace Incoviba\Middleware;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Incoviba\Exception\MissingAuthorizationHeader;

class API
{
    public function __construct(protected ResponseFactoryInterface $responseFactory, protected string $key) {}

    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        try {
            $key = $this->getKey($request);
        } catch (MissingAuthorizationHeader $exception) {
            return $this->responseFactory->createResponse(401);
        }
        if ($this->validate($key)) {
            return $handler->handle($request);
        }
        return $this->responseFactory->createResponse(403);
    }
    protected function getKey(ServerRequestInterface $request): string
    {
        $auth_headers = $request->getHeader('Authorization');
        foreach ($auth_headers as $header) {
            if (str_contains($header, 'Bearer')) {
                return substr($header, strlen('Bearer '));
            }
        }
        throw new MissingAuthorizationHeader();
    }
    protected function validate($incoming_key): bool
    {
        return $incoming_key === md5($this->key);
    }
}
