<?php

namespace Velis\Filesystem\Av\Concrete;

use RuntimeException;
use Velis\Filesystem\Av\Contract\FileHandlerInterface;

/**
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
final class FileHandler implements FileHandlerInterface
{
    public function __construct(
        private readonly string $allowedSourcePath
    ) {
    }

    /**
     * @inheritDoc
     */
    public function processFile(string $filePath): array
    {
        // It is safe to suppress the warning here because it is an internal function.
        // And here we are checking the file path is in the allowed source path.
        // phpcs:disable PHPCS_SecurityAudit.BadFunctions.FilesystemFunctions.WarnFilesystem
        $realPath = realpath($filePath);

        if ($realPath === false || !str_starts_with($realPath, $this->allowedSourcePath)) {
            throw new RuntimeException(
                sprintf('File path %s is not in the secure folder path %s', $filePath, $this->allowedSourcePath)
            );
        }

        $handle = fopen($filePath, 'rb');

        if ($handle === false) {
            throw new RuntimeException(sprintf('Unable to open file: %s', $filePath));
        }

        return ['handle' => $handle, 'fileSize' => (int) filesize($filePath)];
        // phpcs:enable
    }
}
