<?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\DocStoreBundle\Tests\GenericDoc;

use Chill\DocStoreBundle\Entity\StoredObject;
use Chill\DocStoreBundle\GenericDoc\Exception\NotNormalizableGenericDocException;
use Chill\DocStoreBundle\GenericDoc\FetchQuery;
use Chill\DocStoreBundle\GenericDoc\FetchQueryInterface;
use Chill\DocStoreBundle\GenericDoc\GenericDocDTO;
use Chill\DocStoreBundle\GenericDoc\GenericDocForPersonProviderInterface;
use Chill\DocStoreBundle\GenericDoc\GenericDocNormalizerInterface;
use Chill\DocStoreBundle\GenericDoc\Manager;
use Chill\DocStoreBundle\GenericDoc\GenericDocForAccompanyingPeriodProviderInterface;
use Chill\PersonBundle\Entity\AccompanyingPeriod;
use Chill\PersonBundle\Entity\Person;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\EntityManagerInterface;
use Prophecy\PhpUnit\ProphecyTrait;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

/**
 * @internal
 *
 * @coversNothing
 */
class ManagerTest extends KernelTestCase
{
    use ProphecyTrait;
    private EntityManagerInterface $em;

    private Connection $connection;

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

        $this->em = self::getContainer()->get(EntityManagerInterface::class);
        $this->connection = self::getContainer()->get(Connection::class);
    }

    public function testCountByAccompanyingPeriod(): void
    {
        $period = $this->em->createQuery('SELECT a FROM '.AccompanyingPeriod::class.' a')
            ->setMaxResults(1)
            ->getSingleResult();

        if (null === $period) {
            throw new \UnexpectedValueException('period not found');
        }

        $manager = new Manager(
            [new SimpleGenericDocAccompanyingPeriodProvider()],
            [new SimpleGenericDocPersonProvider()],
            [],
            $this->connection,
        );

        $nb = $manager->countDocForAccompanyingPeriod($period);

        self::assertIsInt($nb);
    }

    public function testCountByPerson(): void
    {
        $person = $this->em->createQuery('SELECT a FROM '.Person::class.' a')
            ->setMaxResults(1)
            ->getSingleResult();

        if (null === $person) {
            throw new \UnexpectedValueException('person found');
        }

        $manager = new Manager(
            [new SimpleGenericDocAccompanyingPeriodProvider()],
            [new SimpleGenericDocPersonProvider()],
            [],
            $this->connection,
        );

        $nb = $manager->countDocForPerson($person);

        self::assertIsInt($nb);
    }

    public function testFindDocByAccompanyingPeriod(): void
    {
        $period = $this->em->createQuery('SELECT a FROM '.AccompanyingPeriod::class.' a')
            ->setMaxResults(1)
            ->getSingleResult();

        if (null === $period) {
            throw new \UnexpectedValueException('period not found');
        }

        $manager = new Manager(
            [new SimpleGenericDocAccompanyingPeriodProvider()],
            [new SimpleGenericDocPersonProvider()],
            [],
            $this->connection,
        );

        foreach ($manager->findDocForAccompanyingPeriod($period) as $doc) {
            self::assertInstanceOf(GenericDocDTO::class, $doc);
        }
    }

    public function testFindDocByPerson(): void
    {
        $person = $this->em->createQuery('SELECT a FROM '.Person::class.' a')
            ->setMaxResults(1)
            ->getSingleResult();

        if (null === $person) {
            throw new \UnexpectedValueException('person not found');
        }

        $manager = new Manager(
            [new SimpleGenericDocAccompanyingPeriodProvider()],
            [new SimpleGenericDocPersonProvider()],
            [],
            $this->connection,
        );

        foreach ($manager->findDocForPerson($person) as $doc) {
            self::assertInstanceOf(GenericDocDTO::class, $doc);
        }
    }

    public function testPlacesForPerson(): void
    {
        $person = $this->em->createQuery('SELECT a FROM '.Person::class.' a')
            ->setMaxResults(1)
            ->getSingleResult();

        if (null === $person) {
            throw new \UnexpectedValueException('person not found');
        }

        $manager = new Manager(
            [new SimpleGenericDocAccompanyingPeriodProvider()],
            [new SimpleGenericDocPersonProvider()],
            [],
            $this->connection,
        );

        $places = $manager->placesForPerson($person);

        self::assertEquals(['dummy_person_doc'], $places);
    }

    public function testPlacesForAccompanyingPeriod(): void
    {
        $period = $this->em->createQuery('SELECT a FROM '.AccompanyingPeriod::class.' a')
            ->setMaxResults(1)
            ->getSingleResult();

        if (null === $period) {
            throw new \UnexpectedValueException('period not found');
        }

        $manager = new Manager(
            [new SimpleGenericDocAccompanyingPeriodProvider()],
            [new SimpleGenericDocPersonProvider()],
            [],
            $this->connection,
        );

        $places = $manager->placesForAccompanyingPeriod($period);

        self::assertEquals(['accompanying_course_document_dummy'], $places);
    }

    public function testIsGenericDocNormalizable(): void
    {
        $genericDoc = new GenericDocDTO('test', ['id' => 1], new \DateTimeImmutable(), new AccompanyingPeriod());

        $manager = new Manager([], [], [$this->buildNormalizer(true)], $this->connection);
        self::assertTrue($manager->isGenericDocNormalizable($genericDoc, 'json'));

        $manager = new Manager([], [], [$this->buildNormalizer(false)], $this->connection);
        self::assertFalse($manager->isGenericDocNormalizable($genericDoc, 'json'));
    }

    public function testNormalizeGenericDocMetadata(): void
    {
        $genericDoc = new GenericDocDTO('test', ['id' => 1], new \DateTimeImmutable(), new AccompanyingPeriod());

        $manager = new Manager([], [], [$this->buildNormalizer(false), $this->buildNormalizer(true)], $this->connection);
        self::assertEquals(['title' => 'Some title'], $manager->normalizeGenericDoc($genericDoc, 'json'));
    }

    public function testNormalizeGenericDocMetadataNoNormalizer(): void
    {
        $genericDoc = new GenericDocDTO('test', ['id' => 1], new \DateTimeImmutable(), new AccompanyingPeriod());

        $manager = new Manager([], [], [$this->buildNormalizer(false)], $this->connection);

        $this->expectException(NotNormalizableGenericDocException::class);

        self::assertEquals(['title' => 'Some title'], $manager->normalizeGenericDoc($genericDoc, 'json'));
    }

    public function buildNormalizer(bool $supports): GenericDocNormalizerInterface
    {
        return new class ($supports) implements GenericDocNormalizerInterface {
            public function __construct(private readonly bool $supports) {}

            public function supportsNormalization(GenericDocDTO $genericDocDTO, string $format, array $context = []): bool
            {
                return $this->supports;
            }

            public function normalize(GenericDocDTO $genericDocDTO, string $format, array $context = []): array
            {
                return ['title' => 'Some title'];
            }
        };
    }
}

final readonly class SimpleGenericDocAccompanyingPeriodProvider implements GenericDocForAccompanyingPeriodProviderInterface
{
    public function fetchAssociatedStoredObject(GenericDocDTO $genericDocDTO): ?StoredObject
    {
        throw new \BadMethodCallException('not implemented');
    }

    public function supportsGenericDoc(GenericDocDTO $genericDocDTO): bool
    {
        throw new \BadMethodCallException('not implemented');
    }

    public function supportsKeyAndIdentifiers(string $key, array $identifiers): bool
    {
        return 'accompanying_course_document_dummy' === $key;
    }

    public function buildOneGenericDoc(string $key, array $identifiers): ?GenericDocDTO
    {
        return new GenericDocDTO('accompanying_course_document_dummy', $identifiers, new \DateTimeImmutable(), new AccompanyingPeriod());
    }

    public function buildFetchQueryForAccompanyingPeriod(AccompanyingPeriod $accompanyingPeriod, ?\DateTimeImmutable $startDate = null, ?\DateTimeImmutable $endDate = null, ?string $content = null, ?string $origin = null): FetchQueryInterface
    {
        $query = new FetchQuery(
            'accompanying_course_document_dummy',
            sprintf('jsonb_build_object(\'id\', %s)', 'id'),
            'd',
            '(VALUES (1, \'2023-05-01\'::date), (2, \'2023-05-01\'::date)) AS sq (id, d)',
        );

        $query->addWhereClause('d > ?', [new \DateTimeImmutable('2023-01-01')], [Types::DATE_IMMUTABLE]);

        return $query;
    }

    public function isAllowedForAccompanyingPeriod(AccompanyingPeriod $accompanyingPeriod): bool
    {
        return true;
    }
}

final readonly class SimpleGenericDocPersonProvider implements GenericDocForPersonProviderInterface
{
    public function buildFetchQueryForPerson(Person $person, ?\DateTimeImmutable $startDate = null, ?\DateTimeImmutable $endDate = null, ?string $content = null, ?string $origin = null): FetchQueryInterface
    {
        $query = new FetchQuery(
            'dummy_person_doc',
            sprintf('jsonb_build_object(\'id\', %s)', 'id'),
            'd',
            '(VALUES (1, \'2023-05-01\'::date), (2, \'2023-05-01\'::date)) AS sq (id, d)',
        );

        $query->addWhereClause('d > ?', [new \DateTimeImmutable('2023-01-01')], [Types::DATE_IMMUTABLE]);

        return $query;
    }

    public function isAllowedForPerson(Person $person): bool
    {
        return true;
    }
}
