<?php

namespace App\Tests\Unit\Service\File;

use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\IriConverterInterface;
use ApiPlatform\Metadata\UrlGeneratorInterface;
use App\Entity\Access\Access;
use App\Entity\Core\File;
use App\Entity\Organization\Organization;
use App\Enum\Core\FileTypeEnum;
use App\Enum\Core\FileVisibilityEnum;
use App\Repository\Core\FileRepository;
use App\Service\File\Factory\ImageFactory;
use App\Service\File\FileManager;
use App\Service\File\Storage\FileStorageInterface;
use App\Service\File\Storage\LocalStorage;
use App\Service\ServiceIterator\StorageIterator;
use Doctrine\ORM\EntityManagerInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;

class FileManagerTest extends TestCase
{
    private MockObject|IriConverterInterface $iriConverter;
    private MockObject|StorageIterator $storageIterator;
    private MockObject|ImageFactory $imageFactory;
    private MockObject|LocalStorage $localStorage;

    public function setUp(): void
    {
        $this->iriConverter = $this->getMockBuilder(IriConverterInterface::class)->disableOriginalConstructor()->getMock();
        $this->storageIterator = $this->getMockBuilder(StorageIterator::class)->disableOriginalConstructor()->getMock();
        $this->imageFactory = $this->getMockBuilder(ImageFactory::class)->disableOriginalConstructor()->getMock();
        $this->localStorage = $this->getMockBuilder(LocalStorage::class)->disableOriginalConstructor()->getMock();
        $this->entityManager = $this->getMockBuilder(EntityManagerInterface::class)->disableOriginalConstructor()->getMock();
        $this->fileRepository = $this->getMockBuilder(FileRepository::class)->disableOriginalConstructor()->getMock();
    }

    public function getFileManagerMockFor(string $methodName): FileManager|MockObject
    {
        return $this->getMockBuilder(FileManager::class)
            ->setConstructorArgs([
                $this->iriConverter,
                $this->storageIterator,
                $this->imageFactory,
                $this->localStorage,
                $this->entityManager,
                $this->fileRepository,
            ])
            ->setMethodsExcept([$methodName])
            ->getMock();
    }

    public function testGetStorageFor(): void
    {
        $fileManager = $this->getFileManagerMockFor('getStorageFor');

        $file = $this->getMockBuilder(File::class)->getMock();
        $fileStorage = $this->getMockBuilder(FileStorageInterface::class)->getMock();

        $this->storageIterator->expects(self::once())->method('getStorageFor')->with($file)->willReturn($fileStorage);

        $this->assertEquals(
            $fileStorage,
            $fileManager->getStorageFor($file)
        );
    }

    public function testRead(): void
    {
        $fileManager = $this->getFileManagerMockFor('read');

        $file = $this->getMockBuilder(File::class)->getMock();

        $storage = $this->getMockBuilder(FileStorageInterface::class)->getMock();
        $storage->expects(self::once())->method('read')->with($file)->willReturn('foo');

        $fileManager->expects(self::once())->method('getStorageFor')->with($file)->willReturn($storage);

        $this->assertEquals(
            $fileManager->read($file),
            'foo'
        );
    }

    public function testGetImageUrl(): void
    {
        $fileManager = $this->getFileManagerMockFor('getImageUrl');

        $file = $this->getMockBuilder(File::class)->getMock();
        $fileStorage = $this->getMockBuilder(FileStorageInterface::class)->getMock();

        $fileManager->expects(self::once())->method('getStorageFor')->with($file)->willReturn($fileStorage);

        $fileStorage
            ->method('getImageUrl')
            ->with($file, 'md', true)
            ->willReturn('foo');

        $this->assertEquals(
            'foo',
            $fileManager->getImageUrl($file, 'md', true)
        );
    }

    public function testPrepareFile(): void
    {
        $fileManager = $this->getFileManagerMockFor('prepareFile');

        $owner = $this->createMock(Organization::class);
        $filename = 'example_file.txt';
        $fileType = FileTypeEnum::NONE; // Update with your specific enum type
        $createdBy = $this->createMock(Access::class);
        $isTemporary = false;
        $visibility = FileVisibilityEnum::NOBODY;
        $mimeType = null;
        $flushFile = true;

        $this->localStorage
            ->expects(self::once())
            ->method('prepareFile')
            ->with($owner, $filename, $fileType, $createdBy, $isTemporary, $visibility, $mimeType, $flushFile);

        $file = $fileManager->prepareFile($owner, $filename, $fileType, $createdBy, $isTemporary, $visibility, $mimeType, $flushFile);
    }

    public function testWrite(): void
    {
        $fileManager = $this->getFileManagerMockFor('write');

        $file = $this->createMock(File::class);
        $content = 'Some content';
        $author = $this->createMock(Access::class);

        $this->localStorage
            ->expects(self::once())
            ->method('write')
            ->with($file, $content, $author);

        $result = $fileManager->write($file, $content, $author);
    }

    public function testMakeFile(): void
    {
        $fileManager = $this->getFileManagerMockFor('makeFile');

        $owner = $this->createMock(Organization::class);
        $filename = 'example_file.txt';
        $fileType = FileTypeEnum::NONE; // Update with your specific enum type
        $content = 'Some content';
        $author = $this->createMock(Access::class);
        $isTemporary = false;
        $visibility = FileVisibilityEnum::NOBODY;
        $mimeType = null;

        $this->localStorage
            ->expects(self::once())
            ->method('makeFile')
            ->with($owner, $filename, $fileType, $content, $author, $isTemporary, $visibility, $mimeType);

        $file = $fileManager->makeFile($owner, $filename, $fileType, $content, $author, $isTemporary, $visibility, $mimeType);
    }

    /**
     * @see LocalStorage::getDownloadIri()
     */
    public function testGetDownloadIri(): void
    {
        $fileManager = $this->getFileManagerMockFor('getDownloadIri');

        $file = $this->getMockBuilder(File::class)->getMock();
        $file->method('getId')->willReturn(1);

        $this->iriConverter
            ->expects(self::once())
            ->method('getIriFromResource')
            ->with(File::class, UrlGeneratorInterface::ABS_PATH, new Get(), ['fileId' => 1])
            ->willReturn('/api/download/1');

        $this->assertEquals(
            '/api/download/1',
            $fileManager->getDownloadIri($file)
        );
    }

    public function testDeleteOrganizationFiles(): void
    {
        $fileManager = $this->getFileManagerMockFor('deleteOrganizationFiles');

        $fileStorage1 = $this->getMockBuilder(FileStorageInterface::class)->getMock();
        $fileStorage2 = $this->getMockBuilder(FileStorageInterface::class)->getMock();

        $this->storageIterator->method('getStorages')->willReturn([$fileStorage1, $fileStorage2]);

        $fileStorage1->expects(self::once())->method('deleteOrganizationFiles')->with(123);
        $fileStorage2->expects(self::once())->method('deleteOrganizationFiles')->with(123);

        $this->fileRepository->expects(self::once())->method('deleteByOrganization')->with(123);

        $fileManager->deleteOrganizationFiles(123);
    }

    public function testDeletePersonFiles(): void
    {
        $fileManager = $this->getFileManagerMockFor('deletePersonFiles');

        $fileStorage1 = $this->getMockBuilder(FileStorageInterface::class)->getMock();
        $fileStorage2 = $this->getMockBuilder(FileStorageInterface::class)->getMock();

        $this->storageIterator->method('getStorages')->willReturn([$fileStorage1, $fileStorage2]);

        $fileStorage1->expects(self::once())->method('deletePersonFiles')->with(123);
        $fileStorage2->expects(self::once())->method('deletePersonFiles')->with(123);

        $this->fileRepository->expects(self::once())->method('deleteByPerson')->with(123);

        $fileManager->deletePersonFiles(123);
    }
}
