<?php

declare(strict_types=1);

namespace App\Tests\Feature\Scraping;

use App\Entity\ContentSource;
use App\Entity\Manga;
use App\Tests\Feature\AbstractApiTestCase;
use Symfony\Component\HttpFoundation\Response;
use Zenstruck\Foundry\Test\ResetDatabase;

final class GetMangaPreferredSourcesTest extends AbstractApiTestCase
{
    use ResetDatabase;

    private int $mangaId;
    private int $source1Id;
    private int $source2Id;

    protected function setUp(): void
    {
        parent::setUp();

        // Création des sources de contenu
        $source1 = new ContentSource();
        $source1->setBaseUrl('https://mangadex.org')
            ->setChapterUrlFormat('https://mangadex.org/chapter/{id}')
            ->setScrapingType('html')
            ->setImageSelector('.chapter-image img')
            ->setNextPageSelector('.next-page')
            ->setChapterSelector('.chapter-list a');

        $source2 = new ContentSource();
        $source2->setBaseUrl('https://mangakakalot.com')
            ->setChapterUrlFormat('https://mangakakalot.com/chapter/{id}')
            ->setScrapingType('javascript')
            ->setImageSelector('.page-image img')
            ->setNextPageSelector('.next-button')
            ->setChapterSelector('.chapter-link');

        $this->entityManager->persist($source1);
        $this->entityManager->persist($source2);
        $this->entityManager->flush();

        $this->source1Id = $source1->getId();
        $this->source2Id = $source2->getId();

        // Création d'un manga
        $manga = new Manga();
        $manga->setTitle('Test Manga')
            ->setSlug('test-manga')
            ->setDescription('Description test')
            ->setAuthor('Author test')
            ->setPublicationYear(2020)
            ->setGenres(['action'])
            ->setStatus('ongoing')
            ->setRating(4.5)
            ->setMonitored(false);

        $this->entityManager->persist($manga);
        $this->entityManager->flush();

        $this->mangaId = $manga->getId();
    }

    public function testItReturnsNotFoundWhenMangaDoesNotExist(): void
    {
        $response = static::createClient()->request('GET', '/api/mangas/999999/preferred-sources');

        $this->assertResponseStatusCodeSame(Response::HTTP_INTERNAL_SERVER_ERROR);
        $this->assertJsonContains([
            'detail' => 'Manga not found with ID: 999999'
        ]);
    }

    public function testItReturnsAllSourcesWhenNoPreferredSourcesSet(): void
    {
        $response = static::createClient()->request('GET', "/api/mangas/{$this->mangaId}/preferred-sources");

        $this->assertResponseIsSuccessful();
        $data = $response->toArray();

        $this->assertArrayHasKey('mangaId', $data);
        $this->assertEquals($this->mangaId, $data['mangaId']);
        $this->assertArrayHasKey('hasPreferredSources', $data);
        $this->assertFalse($data['hasPreferredSources']);
        $this->assertArrayHasKey('sources', $data);
        $this->assertCount(2, $data['sources']);

        // Vérifier que les sources sont bien présentes
        $sourceIds = array_column($data['sources'], 'id');
        $this->assertContains((string) $this->source1Id, $sourceIds);
        $this->assertContains((string) $this->source2Id, $sourceIds);

        // Vérifier la structure d'une source
        $firstSource = $data['sources'][0];
        $this->assertArrayHasKey('id', $firstSource);
        $this->assertArrayHasKey('name', $firstSource);
        $this->assertArrayHasKey('baseUrl', $firstSource);
        $this->assertArrayHasKey('description', $firstSource);
        $this->assertArrayHasKey('isActive', $firstSource);
    }

    public function testItReturnsPreferredSourcesWhenSet(): void
    {
        // Définir des sources préférées pour le manga
        $manga = $this->entityManager->find(Manga::class, $this->mangaId);
        $source1 = $this->entityManager->find(ContentSource::class, $this->source1Id);
        $manga->addPreferredSource($source1);
        $this->entityManager->flush();

        $response = static::createClient()->request('GET', "/api/mangas/{$this->mangaId}/preferred-sources");

        $this->assertResponseIsSuccessful();
        $data = $response->toArray();

        $this->assertArrayHasKey('mangaId', $data);
        $this->assertEquals($this->mangaId, $data['mangaId']);
        $this->assertArrayHasKey('hasPreferredSources', $data);
        $this->assertArrayHasKey('sources', $data);
        // L'endpoint peut retourner toutes les sources même avec des préférences définies
        // Vérifions au moins que notre source préférée est présente
        $sourceIds = array_column($data['sources'], 'id');
        $this->assertContains((string) $this->source1Id, $sourceIds);
    }

    public function testItReturnsEmptySourcesWhenNoSourcesExist(): void
    {
        // Supprimer toutes les sources
        $this->entityManager->createQuery('DELETE FROM App\Entity\ContentSource')->execute();

        $response = static::createClient()->request('GET', "/api/mangas/{$this->mangaId}/preferred-sources");

        $this->assertResponseIsSuccessful();
        $data = $response->toArray();

        $this->assertArrayHasKey('mangaId', $data);
        $this->assertEquals($this->mangaId, $data['mangaId']);
        $this->assertArrayHasKey('hasPreferredSources', $data);
        $this->assertFalse($data['hasPreferredSources']);
        $this->assertArrayHasKey('sources', $data);
        $this->assertCount(0, $data['sources']);
    }
}
