<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\WopiBundle\Tests\Service\Wopi;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\MainBundle\Redis\ChillRedis;
use Chill\WopiBundle\Service\Wopi\ChillDocumentLockManager;
use Prophecy\PhpUnit\ProphecyTrait;
use Psr\Http\Message\RequestInterface;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @internal
 *
 * @coversNothing
 */
final class ChillDocumentLockManagerTest extends KernelTestCase
{
    use ProphecyTrait;

    protected function setUp(): void
    {
        self::bootKernel();
    }

    public function testRelock()
    {
        $manager = $this->makeManager(1);
        $document = new StoredObject();
        $request = $this->prophesize(RequestInterface::class);

        $this->assertFalse($manager->hasLock($document, $request->reveal()));

        $this->assertTrue($manager->setLock($document, 'dummy', $request->reveal()));

        $this->assertEquals('dummy', $manager->getLock($document, $request->reveal()));

        $this->assertTrue($manager->setLock($document, 'bar', $request->reveal()));

        $this->assertEquals('bar', $manager->getLock($document, $request->reveal()));

        $this->assertTrue($manager->deleteLock($document, $request->reveal()));

        sleep(3); // wait for redis to remove the key

        $this->assertFalse($manager->hasLock($document, $request->reveal()));
    }

    public function testSingleLock()
    {
        $manager = $this->makeManager(1);
        $document = new StoredObject();
        $request = $this->prophesize(RequestInterface::class);

        $this->assertFalse($manager->hasLock($document, $request->reveal()));

        $this->assertTrue($manager->setLock($document, 'dummy', $request->reveal()));

        $this->assertEquals('dummy', $manager->getLock($document, $request->reveal()));

        $this->assertTrue($manager->deleteLock($document, $request->reveal()));

        sleep(3); // wait for redis to remove the key

        $this->assertFalse($manager->hasLock($document, $request->reveal()));
    }

    private function makeManager(int $ttlAfterDeleteSeconds = -1): ChillDocumentLockManager
    {
        $redis = self::getContainer()->get(ChillRedis::class);

        return new ChillDocumentLockManager($redis, $ttlAfterDeleteSeconds);
    }
}
