<?php
namespace Incoviba\Middleware;

use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

class CORS
{
    public function __construct(protected ResponseFactoryInterface $responseFactory) {}
    public function __invoke(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        if ($request->getMethod() === 'OPTIONS') {
            return $this->responseFactory->createResponse()
                ->withHeader('Access-Control-Allow-Origin', '*')
                ->withHeader('Access-Control-Allow-Methods', 'POST,GET,OPTIONS')
                ->withHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');
        }
        return $handler->handle($request)
            ->withHeader('Access-Control-Allow-Origin', '*');
    }
}
