<?php

declare(strict_types=1);

namespace CpCreation\VitiCore\Tests\Marketing;

use CpCreation\VitiCore\Marketing\Model\AbandonedCartReminder;
use CpCreation\VitiCore\Marketing\Repository\AbandonedCartReminderRepository;
use Doctrine\DBAL\DriverManager;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMSetup;
use Doctrine\Persistence\ManagerRegistry;
use PHPUnit\Framework\TestCase;
use Ramsey\Uuid\Doctrine\UuidType;
use Ramsey\Uuid\Uuid;

final class AbandonedCartReminderRepositoryTest extends TestCase
{
    public function testAdminQueryAppliesSearchStatusAndRuleFilters(): void
    {
        $repository = $this->createRepository();
        $ruleId = Uuid::uuid4()->toString();
        $queryBuilder = $repository->createAdminQueryBuilder(
            search: '  CLIENT@EXAMPLE.COM  ',
            status: AbandonedCartReminder::STATUS_SENT,
            ruleId: $ruleId,
        );
        $dql = $queryBuilder->getDQL();

        self::assertStringContainsString('reminder.recipientEmail', $dql);
        self::assertStringContainsString('cart.token', $dql);
        self::assertStringContainsString('rule.name', $dql);
        self::assertStringContainsString('promo.title', $dql);
        self::assertStringContainsString('reminder.status = :reminderStatus', $dql);
        self::assertStringContainsString('rule.id = :reminderRuleId', $dql);
        self::assertSame('%client@example.com%', $queryBuilder->getParameter('reminderSearch')?->getValue());
        self::assertSame(AbandonedCartReminder::STATUS_SENT, $queryBuilder->getParameter('reminderStatus')?->getValue());
        self::assertSame($ruleId, $queryBuilder->getParameter('reminderRuleId')?->getValue());
    }

    public function testAdminQueryIgnoresAnInvalidStatus(): void
    {
        $queryBuilder = $this->createRepository()->createAdminQueryBuilder(status: 'unknown');

        self::assertNull($queryBuilder->getParameter('reminderStatus'));
    }

    private function createRepository(): AbandonedCartReminderRepository
    {
        if (!Type::hasType('uuid')) {
            Type::addType('uuid', UuidType::class);
        }

        $configuration = ORMSetup::createAttributeMetadataConfiguration([
            \dirname(__DIR__, 2) . '/src/Marketing/Model',
        ], true);
        $connection = DriverManager::getConnection([
            'driver' => 'pdo_sqlite',
            'memory' => true,
        ], $configuration);
        $entityManager = new EntityManager($connection, $configuration);
        $registry = $this->createMock(ManagerRegistry::class);
        $registry->method('getManagerForClass')
            ->with(AbandonedCartReminder::class)
            ->willReturn($entityManager);

        return new AbandonedCartReminderRepository($registry);
    }
}
