<?php

namespace App\Tests\Unit\Service\File\Storage;

use ApiPlatform\Core\Api\IriConverterInterface;
use App\Entity\Access\Access;
use App\Entity\Core\File;
use App\Entity\Organization\Organization;
use App\Entity\Person\Person;
use App\Enum\Core\FileStatusEnum;
use App\Enum\Core\FileTypeEnum;
use App\Repository\Access\AccessRepository;
use App\Service\File\Storage\LocalStorage;
use DateTime;
use Doctrine\ORM\EntityManagerInterface;
use Gaufrette\Filesystem;
use JetBrains\PhpStorm\Pure;
use Knp\Bundle\GaufretteBundle\FilesystemMap;
use PHPUnit\Framework\TestCase;
use RuntimeException;

class TestableLocalStorage extends LocalStorage {
    public const FS_KEY = parent::FS_KEY;

    public function getPrefix(mixed $owner, bool $isTemporary, string $type = null): string {
        return parent::getPrefix($owner, $isTemporary, $type);
    }
    #[Pure] public function getOrganizationAndPersonFromOwner(mixed $owner): array {
        return parent::getOrganizationAndPersonFromOwner($owner);
    }
}


class LocalStorageTest extends TestCase
{
    private FilesystemMap $filesystemMap;
    private EntityManagerInterface $entityManager;
    private AccessRepository $accessRepository;
    private Filesystem $filesystem;
    private IriConverterInterface $iriConverter;

    public function setUp(): void
    {
        $this->filesystemMap = $this->getMockBuilder(FilesystemMap::class)->disableOriginalConstructor()->getMock();
        $this->entityManager = $this->getMockBuilder(EntityManagerInterface::class)->disableOriginalConstructor()->getMock();
        $this->accessRepository = $this->getMockBuilder(AccessRepository::class)->disableOriginalConstructor()->getMock();
        $this->iriConverter = $this->getMockBuilder(IriConverterInterface::class)->disableOriginalConstructor()->getMock();

        $this->filesystem = $this->getMockBuilder(Filesystem::class)->disableOriginalConstructor()->getMock();
        $this->filesystemMap->method('get')->with(TestableLocalStorage::FS_KEY)->willReturn($this->filesystem);
    }

    /**
     * @see LocalStorage::exists()
     */
    public function testExists(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['exists'])
            ->getMock();

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

        $this->filesystem->expects(self::once())->method('has')->with('foo')->willReturn(true);

        $this->assertTrue($fileStorage->exists($file));
    }

    /**
     * @see LocalStorage::exists()
     */
    public function testExistsInexistant(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['exists'])
            ->getMock();

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

        $this->filesystem->expects(self::once())->method('has')->with('foo')->willReturn(false);

        $this->assertFalse($fileStorage->exists($file));
    }


    /**
     * @see LocalStorage::listByOwner()
     */
    public function testListByOwner(): void
    {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['listByOwner'])
            ->getMock();

        $owner = $this->getMockBuilder(Organization::class)->getMock();

        $fileStorage->method('getPrefix')->with($owner, false, FileTypeEnum::LICENCE_CMF()->getValue())->willReturn('foo');

        $this->filesystem->method('listKeys')->with('foo')->willReturn(['foo/a.txt', 'foo/b.pdf']);

        $this->assertEquals(
            ['foo/a.txt', 'foo/b.pdf'],
            $fileStorage->listByOwner($owner, FileTypeEnum::LICENCE_CMF())
        );
    }

    /**
     * @see LocalStorage::read()
     */
    public function testRead(): void
    {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['read'])
            ->getMock();

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

        $this->filesystem->method('read')->with('foo')->willReturn('12345679');

        $this->assertEquals(
            '12345679',
            $fileStorage->read($file)
        );
    }

    /**
     * @see LocalStorage::prepareFile()
     */
    public function testPrepareFile(): void
    {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['prepareFile'])
            ->getMock();

        $owner = $this->getMockBuilder(Organization::class)->getMock();
        $author = $this->getMockBuilder(Access::class)->getMock();
        $author->method('getId')->willReturn(123);

        $fileStorage->method('getOrganizationAndPersonFromOwner')->with($owner)->willReturn([$owner, null]);

        $this->entityManager->expects(self::once())->method('persist');
        $this->entityManager->expects(self::once())->method('flush');

        $file = $fileStorage->prepareFile(
            $owner,
            'file.ext',
            FileTypeEnum::LICENCE_CMF(),
            $author,
            true,
            'ONLY_ORGANIZATION',
            'application/pdf'
        );

        $this->assertEquals($owner, $file->getOrganization());
        $this->assertEquals(null, $file->getPerson());
        $this->assertEquals('file.ext', $file->getName());
        $this->assertEquals(null, $file->getSlug());
        $this->assertEquals(FileTypeEnum::LICENCE_CMF()->getValue(), $file->getType());
        $this->assertEquals(true, $file->getIsTemporaryFile());
        $this->assertEquals('ONLY_ORGANIZATION', $file->getVisibility());
        $this->assertEquals('application/pdf', $file->getMimeType());
        $this->assertEquals(123, $file->getCreatedBy());

    }

    /**
     * @see LocalStorage::prepareFile()
     */
    public function testPrepareFileDefaultValues(): void
    {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['prepareFile'])
            ->getMock();

        $owner = $this->getMockBuilder(Person::class)->getMock();
        $author = $this->getMockBuilder(Access::class)->getMock();

        $fileStorage->method('getOrganizationAndPersonFromOwner')->with($owner)->willReturn([null, $owner]);

        $this->entityManager->expects(self::once())->method('persist');
        $this->entityManager->expects(self::once())->method('flush');

        $file = $fileStorage->prepareFile($owner, 'file.txt', FileTypeEnum::NONE(), $author);

        $this->assertEquals(null, $file->getOrganization());
        $this->assertEquals($owner, $file->getPerson());
        $this->assertEquals('file.txt', $file->getName());
        $this->assertEquals(FileTypeEnum::NONE()->getValue(), $file->getType());
        $this->assertEquals(false, $file->getIsTemporaryFile());
        $this->assertEquals('NOBODY', $file->getVisibility());
        $this->assertEquals('text/plain', $file->getMimeType());
    }

    /**
     * @see LocalStorage::prepareFile()
     */
    public function testPrepareFileNoFlush(): void
    {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['prepareFile'])
            ->getMock();

        $owner = $this->getMockBuilder(Organization::class)->getMock();
        $author = $this->getMockBuilder(Access::class)->getMock();

        $fileStorage->method('getOrganizationAndPersonFromOwner')->with($owner)->willReturn([$owner, null]);

        $this->entityManager->expects(self::once())->method('persist');
        $this->entityManager->expects(self::never())->method('flush');

        $fileStorage->prepareFile(
            $owner,
            'file.txt',
            FileTypeEnum::NONE(),
            $author,
            false,
            'NOBODY',
            null,
            false
        );
    }

    /**
     * @see LocalStorage::writeFile()
     */
    public function testWriteFileNewFile(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['writeFile'])
            ->getMock();

        $organization = $this->getMockBuilder(Organization::class)->getMock();

        $author = $this->getMockBuilder(Access::class)->getMock();
        $author->method('getId')->willReturn(123);

        $file = $this->getMockBuilder(File::class)->getMock();
        $file->method('getName')->willReturn('foo.txt');
        $file->method('getOrganization')->willReturn($organization);
        $file->method('getPerson')->willReturn(null);
        $file->method('getIsTemporaryFile')->willReturn(false);
        $file->method('getSlug')->willReturn(null);
        $file->method('getType')->willReturn(FileTypeEnum::NONE()->getValue());

        $fileStorage
            ->method('getPrefix')
            ->with($organization, false, FileTypeEnum::NONE()->getValue())
            ->willReturn('prefix/');

        $content = '123456789';
        $size = strlen($content);

        $this->filesystem
            ->expects(self::once())
            ->method('write')
            ->with(self::matchesRegularExpression('/^prefix\/\w{16,24}\/foo.txt/'), $content, true)
            ->willReturn($size);

        $file->expects(self::once())->method('setSize')->with($size)->willReturnSelf();
        $file->expects(self::once())->method('setStatus')->with(FileStatusEnum::READY()->getValue())->willReturnSelf();
        $file->expects(self::once())
            ->method('setSlug')
            ->with(self::matchesRegularExpression('/^prefix\/\w{16,24}\/foo.txt/'))
            ->willReturnSelf();
        $file->expects(self::once())->method('setCreateDate')->with(self::isInstanceOf(DateTime::class))->willReturnSelf();
        $file->expects(self::once())->method('setCreatedBy')->with(123)->willReturnSelf();
        $file->expects(self::never())->method('setUpdateDate');
        $file->expects(self::never())->method('setUpdatedBy');

        $this->entityManager->expects(self::once())->method('flush');

        $returned = $fileStorage->writeFile($file, $content, $author);

        $this->assertEquals($file, $returned);
    }

    /**
     * @see LocalStorage::writeFile()
     */
    public function testWriteFileExistingFile(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['writeFile'])
            ->getMock();

        $person = $this->getMockBuilder(Person::class)->getMock();

        $author = $this->getMockBuilder(Access::class)->getMock();
        $author->method('getId')->willReturn(123);

        $key = 'prefix/uid/bar.txt';

        $file = $this->getMockBuilder(File::class)->getMock();
        $file->method('getName')->willReturn('bar.txt');
        $file->method('getOrganization')->willReturn(null);
        $file->method('getPerson')->willReturn($person);
        $file->method('getIsTemporaryFile')->willReturn(true);
        $file->method('getSlug')->willReturn($key);
        $file->method('getType')->willReturn(FileTypeEnum::NONE()->getValue());

        $fileStorage->expects(self::never())->method('getPrefix');

        $content = '123 Soleil';
        $size = strlen($content);

        $this->filesystem
            ->expects(self::once())
            ->method('write')
            ->with($key, $content, true)
            ->willReturn($size);

        $this->filesystem->method('has')->with($key)->willReturn(true);

        $file->expects(self::once())->method('setSize')->with($size)->willReturnSelf();
        $file->expects(self::once())->method('setStatus')->with(FileStatusEnum::READY()->getValue())->willReturnSelf();
        $file->expects(self::never())->method('setSlug');
        $file->expects(self::never())->method('setCreateDate');
        $file->expects(self::never())->method('setCreatedBy');
        $file->expects(self::once())->method('setUpdateDate')->with(self::isInstanceOf(DateTime::class))->willReturnSelf();
        $file->expects(self::once())->method('setUpdatedBy')->with(123)->willReturnSelf();

        $this->entityManager->expects(self::once())->method('flush');

        $returned = $fileStorage->writeFile($file, $content, $author);

        $this->assertEquals($file, $returned);
    }

    /**
     * @see LocalStorage::writeFile()
     */
    public function testWriteFileExistingButMissingFile(): void
    {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['writeFile'])
            ->getMock();

        $person = $this->getMockBuilder(Person::class)->getMock();
        $author = $this->getMockBuilder(Access::class)->getMock();

        $key = 'prefix/uid/bar.txt';

        $file = $this->getMockBuilder(File::class)->getMock();
        $file->method('getName')->willReturn('bar.txt');
        $file->method('getOrganization')->willReturn(null);
        $file->method('getPerson')->willReturn($person);
        $file->method('getIsTemporaryFile')->willReturn(true);
        $file->method('getSlug')->willReturn($key);
        $file->method('getType')->willReturn(FileTypeEnum::NONE()->getValue());

        $this->filesystem->expects(self::never())->method('write');
        $this->entityManager->expects(self::never())->method('flush');

        $this->filesystem->method('has')->with($key)->willReturn(false);

        $this->expectException(RuntimeException::class);
        $this->expectDeprecationMessage('The file `' . $key . '` does not exist in the file storage');

        $fileStorage->writeFile($file, '12346', $author);
    }

    /**
     * @see LocalStorage::writeFile()
     */
    public function testWriteFileWithAccessOwner(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['writeFile'])
            ->getMock();

        $access = $this->getMockBuilder(Access::class)->getMock();
        $person = $this->getMockBuilder(Person::class)->getMock();
        $organization = $this->getMockBuilder(Organization::class)->getMock();

        $author = $this->getMockBuilder(Access::class)->getMock();
        $author->method('getId')->willReturn(123);

        $file = $this->getMockBuilder(File::class)->getMock();
        $file->method('getName')->willReturn('bar.txt');
        $file->method('getOrganization')->willReturn($organization);
        $file->method('getPerson')->willReturn($person);
        $file->method('getIsTemporaryFile')->willReturn(true);
        $file->method('getSlug')->willReturn(null);
        $file->method('getType')->willReturn(FileTypeEnum::NONE()->getValue());

        $this->accessRepository
            ->expects(self::once())
            ->method('findOneBy')
            ->with(['organization' => $organization, 'person' => $person])
            ->willReturn($access);

        $fileStorage
            ->expects(self::once())
            ->method('getPrefix')
            ->with($access, true, FileTypeEnum::NONE()->getValue())
            ->willReturn('prefix/');

        $content = '1';
        $this->filesystem->method('write')->willReturn(1);

        $fileStorage->writeFile($file, $content, $author);
    }

    /**
     * @see LocalStorage::writeFile()
     */
    public function testWriteFileWithNoName(): void
    {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['writeFile'])
            ->getMock();

        $author = $this->getMockBuilder(Access::class)->getMock();

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

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('File has no filename');

        $fileStorage->writeFile($file, '...', $author);
    }

    /**
     * @see LocalStorage::makeFile()
     */
    public function testMakeFile(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['makeFile'])
            ->getMock();

        $organization = $this->getMockBuilder(Organization::class)->getMock();
        $author = $this->getMockBuilder(Access::class)->getMock();
        $file = $this->getMockBuilder(File::class)->getMock();

        $fileStorage
            ->expects(self::once())
            ->method('prepareFile')
            ->with($organization, 'foo.txt', FileTypeEnum::NONE(), $author, true, 'ONLY_ORGANIZATION', 'mime/type')
            ->willReturn($file);

        $fileStorage
            ->expects(self::once())
            ->method('writeFile')
            ->with($file, '...', $author)
            ->willReturn($file);

        $fileStorage->makeFile(
            $organization,
            'foo.txt',
            FileTypeEnum::NONE(),
            '...',
            $author,
            true,
            'ONLY_ORGANIZATION',
            'mime/type');
    }

    /**
     * @see LocalStorage::delete()
     */
    public function testDelete(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['delete'])
            ->getMock();

        $author = $this->getMockBuilder(Access::class)->getMock();
        $author->method('getId')->willReturn(123);

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

        $this->filesystem->expects(self::once())->method('delete')->with('key')->willReturn(true);

        $file->expects(self::once())->method('setStatus')->with(FileStatusEnum::DELETED()->getValue())->willReturnSelf();
        $file->expects(self::once())->method('setSize')->with(0)->willReturnSelf();
        $file->expects(self::once())->method('setUpdatedBy')->with(123)->willReturnSelf();

        $returned = $fileStorage->delete($file, $author);

        $this->assertEquals($file, $returned);
    }

    /**
     * @see LocalStorage::delete()
     */
    public function testDeleteFailed(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['delete'])
            ->getMock();

        $author = $this->getMockBuilder(Access::class)->getMock();
        $author->method('getId')->willReturn(123);

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

        $this->filesystem->expects(self::once())->method('delete')->with('key')->willReturn(false);

        $file->expects(self::never())->method('setStatus');
        $file->expects(self::never())->method('setSize');
        $file->expects(self::never())->method('setUpdatedBy');

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('File `' . $file->getSlug() . '` could\'nt be deleted');

        $fileStorage->delete($file, $author);
    }

    /**
     * @see LocalStorage::getPrefix()
     */
    public function testGetPrefixAccess(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['getPrefix'])
            ->getMock();

        $organization = $this->getMockBuilder(Organization::class)->getMock();
        $organization->method('getId')->willReturn(2);

        $access = $this->getMockBuilder(Access::class)->getMock();
        $access->method('getOrganization')->willReturn($organization);
        $access->method('getId')->willReturn(1);

        $prefix = $fileStorage->getPrefix($access, false);

        $this->assertEquals('organization/2/1', $prefix);
    }

    /**
     * @see LocalStorage::getPrefix()
     */
    public function testGetPrefixOrganization(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['getPrefix'])
            ->getMock();

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

        $prefix = $fileStorage->getPrefix($organization, false);

        $this->assertEquals('organization/1', $prefix);
    }

    /**
     * @see LocalStorage::getPrefix()
     */
    public function testGetPrefixPerson(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['getPrefix'])
            ->getMock();

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

        $prefix = $fileStorage->getPrefix($person, false);

        $this->assertEquals('person/1', $prefix);
    }

    /**
     * @see LocalStorage::getPrefix()
     */
    public function testGetPrefixTemp(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['getPrefix'])
            ->getMock();

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

        $prefix = $fileStorage->getPrefix($organization, true);

        $this->assertEquals('temp/organization/1', $prefix);
    }

    /**
     * @see LocalStorage::getPrefix()
     */
    public function testGetPrefixWithType(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['getPrefix'])
            ->getMock();

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

        $prefix = $fileStorage->getPrefix($organization, false, FileTypeEnum::LICENCE_CMF()->getValue());

        $this->assertEquals('organization/1/licence_cmf', $prefix);
    }

    /**
     * @see LocalStorage::getOrganizationAndPersonFromOwner()
     */
    public function testGetOrganizationAndPersonFromOwner(): void {
        $fileStorage = $this->getMockBuilder(TestableLocalStorage::class)
            ->setConstructorArgs([$this->filesystemMap, $this->entityManager, $this->accessRepository, $this->iriConverter])
            ->setMethodsExcept(['getOrganizationAndPersonFromOwner'])
            ->getMock();

        $organization = $this->getMockBuilder(Organization::class)->getMock();
        $organization->method('getId')->willReturn(2);

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

        $access = $this->getMockBuilder(Access::class)->getMock();
        $access->method('getOrganization')->willReturn($organization);
        $access->method('getPerson')->willReturn($person);
        $access->method('getId')->willReturn(1);

        $this->assertEquals([$organization, $person], $fileStorage->getOrganizationAndPersonFromOwner($access));
        $this->assertEquals([$organization, null], $fileStorage->getOrganizationAndPersonFromOwner($organization));
        $this->assertEquals([null, $person], $fileStorage->getOrganizationAndPersonFromOwner($person));
    }
}
