<?php

namespace Velis\Test\Filesystem\Adapter;

use Aws\S3\S3Client;
use RuntimeException;
use Velis\App;
use Velis\App\Config;
use Velis\Cache\CacheInterface;
use Velis\Filesystem\Adapter\UploadFilesystemFactory;
use Velis\Filesystem\FilesystemInterface;
use Velis\TestCase;

/**
 * @author Szymon Janaczek <szymon.janaczek@velistech.com>
 */
final class UploadFilesystemFactoryTest extends TestCase
{
    public function testGetVelisFilesystem(): void
    {
        $config = new Config([
            'upload' => [
                'alternativeDir' => null,
                'filesystem' => 'local',
            ],
        ]);

        $cache = $this->createMock(CacheInterface::class);

        $filesystem = new UploadFilesystemFactory(config: $config, cache: $cache);
        $result = $filesystem->getVelisFilesystem('uploadPath');

        $this->assertInstanceOf(FilesystemInterface::class, $result);
    }

    public function testGetLocal(): void
    {
        $config = new Config([
            'upload' => [
                'alternativeDir' => null,
                'filesystem' => 'local',
            ],
        ]);

        $cache = $this->createMock(CacheInterface::class);

        $filesystem = new UploadFilesystemFactory(config: $config, cache: $cache);
        $result = $filesystem->get('uploadPath');

        $this->assertInstanceOf(FilesystemInterface::class, $result);
    }

    public function testPrepareUploadS3Success(): void
    {
        $config = new Config([
            'upload' => [
                'alternativeDir' => null,
                'filesystem' => 's3',
                's3' => [
                    'bucketName' => 'bucket-name',
                    'region' => 'eu-west-1',
                    'accessKeyId' => 'key-id',
                    'secretAccessKey' => 'secret-key',
                    'cacheTtl' => 1,
                ],
            ],
        ]);

        $cache = $this->createMock(CacheInterface::class);
        $cache->method('get')->willReturn(null);

        $filesystem = new UploadFilesystemFactory(
            config: $config,
            cache: $cache,
        );
        $result = $filesystem->getS3();

        $this->assertInstanceOf(FilesystemInterface::class, $result);
    }

    public function testPrepareUploadS3MissingCache(): void
    {
        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('S3 filesystem requires cache. Register `cache` service.');

        $config = $this->createMock(Config::class);

        $filesystem = new UploadFilesystemFactory(
            config: $config,
            cache: null,
        );
        $result = $filesystem->getS3();

        $this->assertInstanceOf(FilesystemInterface::class, $result);
    }
}
