<?php

namespace App\Tests\Command;

use App\Command\MeilisearchConsistencyCommand;
use App\Entity\BilletBuyer;
use App\Entity\Event;
use App\Entity\User;
use App\Service\EventIndexService;
use App\Service\MeilisearchService;
use App\Service\OrderIndexService;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;

class MeilisearchConsistencyCommandTest extends TestCase
{
    private MeilisearchService $meilisearch;
    private EntityManagerInterface $em;
    private EventIndexService $eventIndex;
    private OrderIndexService $orderIndex;
    private CommandTester $tester;

    protected function setUp(): void
    {
        $this->meilisearch = $this->createMock(MeilisearchService::class);
        $this->em = $this->createMock(EntityManagerInterface::class);
        $this->eventIndex = $this->createMock(EventIndexService::class);
        $this->orderIndex = $this->createMock(OrderIndexService::class);

        $command = new MeilisearchConsistencyCommand(
            $this->meilisearch,
            $this->em,
            $this->eventIndex,
            $this->orderIndex,
        );

        $app = new Application();
        $app->addCommand($command);
        $this->tester = new CommandTester($app->find('app:meilisearch:check-consistency'));
    }

    public function testAllConsistent(): void
    {
        $this->meilisearch->method('listIndexes')->willReturn(['event_global', 'event_admin']);
        $this->meilisearch->method('indexExists')->willReturnCallback(
            fn (string $idx) => \in_array($idx, ['event_global', 'event_admin'], true)
        );
        $this->meilisearch->method('getAllDocumentIds')->willReturn([1, 2]);

        $event1 = $this->createMock(Event::class);
        $event1->method('getId')->willReturn(1);
        $event2 = $this->createMock(Event::class);
        $event2->method('getId')->willReturn(2);

        $eventRepo = $this->createMock(EntityRepository::class);
        $eventRepo->method('findBy')->willReturn([$event1, $event2]);
        $eventRepo->method('findAll')->willReturn([$event1, $event2]);

        $userRepo = $this->createMock(EntityRepository::class);
        $userRepo->method('findBy')->willReturn([]);
        $userRepo->method('findAll')->willReturn([]);

        $this->em->method('getRepository')->willReturnMap([
            [Event::class, $eventRepo],
            [User::class, $userRepo],
            [BilletBuyer::class, $this->createMock(EntityRepository::class)],
        ]);

        $this->tester->execute([]);
        $this->assertStringContainsString('All indexes are consistent', $this->tester->getDisplay());
    }

    public function testMeilisearchUnreachable(): void
    {
        $this->meilisearch->method('listIndexes')->willThrowException(new \RuntimeException('Connection refused'));

        $this->tester->execute([]);
        $this->assertStringContainsString('Meilisearch unreachable', $this->tester->getDisplay());
        $this->assertSame(1, $this->tester->getStatusCode());
    }

    public function testDetectsOrphansAndMissing(): void
    {
        $this->meilisearch->method('listIndexes')->willReturn(['event_global', 'event_admin']);
        $this->meilisearch->method('indexExists')->willReturn(true);
        $this->meilisearch->method('getAllDocumentIds')->willReturn([1, 99]);

        $event1 = $this->createMock(Event::class);
        $event1->method('getId')->willReturn(1);
        $event2 = $this->createMock(Event::class);
        $event2->method('getId')->willReturn(2);

        $eventRepo = $this->createMock(EntityRepository::class);
        $eventRepo->method('findBy')->willReturn([$event1, $event2]);
        $eventRepo->method('findAll')->willReturn([$event1, $event2]);

        $userRepo = $this->createMock(EntityRepository::class);
        $userRepo->method('findBy')->willReturn([]);
        $userRepo->method('findAll')->willReturn([]);

        $this->em->method('getRepository')->willReturnMap([
            [Event::class, $eventRepo],
            [User::class, $userRepo],
            [BilletBuyer::class, $this->createMock(EntityRepository::class)],
        ]);

        $this->tester->execute([]);
        $output = $this->tester->getDisplay();
        $this->assertStringContainsString('orphan', $output);
        $this->assertStringContainsString('missing', $output);
        $this->assertStringContainsString('--fix', $output);
    }

    public function testFixDeletesOrphansAndReindexes(): void
    {
        $this->meilisearch->method('listIndexes')->willReturn(['event_global', 'event_admin']);
        $this->meilisearch->method('indexExists')->willReturn(true);
        $this->meilisearch->method('getAllDocumentIds')->willReturn([1, 99]);

        $event1 = $this->createMock(Event::class);
        $event1->method('getId')->willReturn(1);
        $event2 = $this->createMock(Event::class);
        $event2->method('getId')->willReturn(2);

        $eventRepo = $this->createMock(EntityRepository::class);
        $eventRepo->method('findBy')->willReturn([$event1, $event2]);
        $eventRepo->method('findAll')->willReturn([$event1, $event2]);

        $userRepo = $this->createMock(EntityRepository::class);
        $userRepo->method('findBy')->willReturn([]);
        $userRepo->method('findAll')->willReturn([]);

        $this->em->method('getRepository')->willReturnMap([
            [Event::class, $eventRepo],
            [User::class, $userRepo],
            [BilletBuyer::class, $this->createMock(EntityRepository::class)],
        ]);

        $this->meilisearch->expects($this->atLeastOnce())->method('deleteDocuments');
        $this->eventIndex->expects($this->atLeastOnce())->method('indexEvent');

        $this->tester->execute(['--fix' => true]);
        $output = $this->tester->getDisplay();
        $this->assertStringContainsString('Fixed', $output);
    }
}
