<?php

declare(strict_types=1);

namespace Doctrine\Tests;

use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Driver;
use Doctrine\DBAL\Driver\Result;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Platforms\SQLitePlatform;
use Doctrine\ORM\Cache\CacheConfiguration;
use Doctrine\ORM\Cache\CacheFactory;
use Doctrine\ORM\Cache\DefaultCacheFactory;
use Doctrine\ORM\Cache\Logging\StatisticsCacheLogger;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\Mapping\Driver\AttributeDriver;
use Doctrine\Tests\Mocks\AttributeDriverFactory;
use Doctrine\Tests\Mocks\EntityManagerMock;
use PHPUnit\Framework\TestCase;
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\Adapter\ArrayAdapter;

use function class_exists;
use function method_exists;
use function sprintf;

// DBAL 3 compatibility
class_exists('Doctrine\\DBAL\\Platforms\\SqlitePlatform');

/**
 * Base testcase class for all ORM testcases.
 */
abstract class OrmTestCase extends TestCase
{
    /**
     * The metadata cache that is shared between all ORM tests (except functional tests).
     */
    private static CacheItemPoolInterface|null $metadataCache = null;

    /**
     * The query cache that is shared between all ORM tests (except functional tests).
     */
    private static CacheItemPoolInterface|null $queryCache = null;

    /** @var bool */
    protected $isSecondLevelCacheEnabled = false;

    /** @var bool */
    protected $isSecondLevelCacheLogEnabled = false;

    /** @var CacheFactory */
    protected $secondLevelCacheFactory;

    /** @var StatisticsCacheLogger */
    protected $secondLevelCacheLogger;

    private CacheItemPoolInterface|null $secondLevelCache = null;

    /** @param list<string> $paths */
    protected function createAttributeDriver(array $paths = []): AttributeDriver
    {
        return AttributeDriverFactory::createAttributeDriver($paths);
    }

    /**
     * Creates an EntityManager for testing purposes.
     *
     * NOTE: The created EntityManager will have its dependant DBAL parts completely
     * mocked out using a DriverMock, ConnectionMock, etc. These mocks can then
     * be configured in the tests to simulate the DBAL behavior that is desired
     * for a particular test,
     */
    protected function getTestEntityManager(): EntityManagerMock
    {
        return $this->createTestEntityManagerWithPlatform(new SQLitePlatform());
    }

    protected function createTestEntityManagerWithConnection(Connection $connection): EntityManagerMock
    {
        return $this->buildTestEntityManagerWithPlatform($connection);
    }

    protected function createTestEntityManagerWithPlatform(AbstractPlatform $platform): EntityManagerMock
    {
        return $this->buildTestEntityManagerWithPlatform(
            $this->createConnectionStub($platform),
        );
    }

    private function buildTestEntityManagerWithPlatform(Connection $connection): EntityManagerMock
    {
        $metadataCache = self::getSharedMetadataCacheImpl();

        $config = new Configuration();

        TestUtil::configureProxies($config);
        $config->setMetadataCache($metadataCache);
        $config->setQueryCache(self::getSharedQueryCache());
        $config->setMetadataDriverImpl(AttributeDriverFactory::createAttributeDriver([__DIR__ . '/Models/Cache']));

        if ($this->isSecondLevelCacheEnabled) {
            $cacheConfig = new CacheConfiguration();
            $factory     = new DefaultCacheFactory(
                $cacheConfig->getRegionsConfiguration(),
                $this->getSharedSecondLevelCache(),
            );

            $this->secondLevelCacheFactory = $factory;

            $cacheConfig->setCacheFactory($factory);
            $config->setSecondLevelCacheEnabled();
            $config->setSecondLevelCacheConfiguration($cacheConfig);
        }

        return new EntityManagerMock($connection, $config);
    }

    protected function enableSecondLevelCache(bool $log = true): void
    {
        $this->isSecondLevelCacheEnabled    = true;
        $this->isSecondLevelCacheLogEnabled = $log;
    }

    private static function getSharedMetadataCacheImpl(): CacheItemPoolInterface
    {
        return self::$metadataCache
            ?? self::$metadataCache = new ArrayAdapter();
    }

    private static function getSharedQueryCache(): CacheItemPoolInterface
    {
        return self::$queryCache
            ?? self::$queryCache = new ArrayAdapter();
    }

    protected function getSharedSecondLevelCache(): CacheItemPoolInterface
    {
        return $this->secondLevelCache
            ?? $this->secondLevelCache = new ArrayAdapter();
    }

    private function createConnectionStub(AbstractPlatform $platform): Connection
    {
        $connection = $this->getMockBuilder(Connection::class)
            ->setConstructorArgs([[], $this->createDriverStub($platform)])
            ->onlyMethods(['quote'])
            ->getMock();
        $connection->method('quote')->willReturnCallback(static fn (string $input) => sprintf("'%s'", $input));

        return $connection;
    }

    private function createDriverStub(AbstractPlatform $platform): Driver
    {
        $result = $this->createStub(Result::class);
        $result->method('fetchAssociative')
            ->willReturn(false);

        $connection = $this->createStub(Driver\Connection::class);
        $connection->method('query')
            ->willReturn($result);

        $driver = $this->createStub(Driver::class);
        $driver->method('connect')
            ->willReturn($connection);
        $driver->method('getDatabasePlatform')
            ->willReturn($platform);

        if (method_exists(Driver::class, 'getSchemaManager')) {
            $driver->method('getSchemaManager')
                ->willReturnCallback([$platform, 'createSchemaManager']);
        }

        return $driver;
    }
}
