<?php

declare(strict_types=1);

namespace app\vendor\apexl\io\src\Io\middleware;

use apexl\Io\services\FilePaths;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

final readonly class AddBuildHeader implements MiddlewareInterface
{
    public function __construct(private FilePaths $filePaths) {}

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = $handler->handle($request);

        $buildFile = $this->filePaths->configDir('build');

        if (file_exists($buildFile)) {
            $build = trim(file_get_contents($buildFile));
            $response = $response->withHeader('X-Build', $build);
        }

        return $response;
    }
}
