<?php

declare(strict_types=1);

namespace App\Tests\Feature\Scraping;

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

final class CheckAllScrapersHealthTest extends AbstractApiTestCase
{
    use ResetDatabase;

    private function post(): void
    {
        static::createClient()->request('POST', '/api/scraping/check-all-health', [
            'json' => new \stdClass(),
        ]);
    }

    public function testItReturns202WithNoSources(): void
    {
        $this->post();

        $this->assertResponseStatusCodeSame(Response::HTTP_ACCEPTED);
    }

    public function testItReturns202WithSourcesHavingNoTestConfig(): void
    {
        $source = new ContentSource();
        $source->setBaseUrl('https://example.com')
               ->setChapterUrlFormat('https://example.com/{slug}/{chapterNumber}')
               ->setScrapingType('html');

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

        $this->post();

        $this->assertResponseStatusCodeSame(Response::HTTP_ACCEPTED);

        // La source sans testSlug ne doit pas avoir son statut modifié
        $this->entityManager->clear();
        $reloaded = $this->entityManager->find(ContentSource::class, $source->getId());
        $this->assertSame('unknown', $reloaded->getHealthStatus());
    }

    public function testHealthStatusIsUpdatedForSourcesWithTestConfig(): void
    {
        $source = new ContentSource();
        $source->setBaseUrl('https://example.com')
               ->setChapterUrlFormat('https://example.com/{slug}/{chapterNumber}')
               ->setScrapingType('html')
               ->setTestSlug('one-piece')
               ->setTestChapterNumber(1.0);

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

        $this->post();

        $this->assertResponseStatusCodeSame(Response::HTTP_ACCEPTED);

        // Le statut ne doit plus être 'unknown' après le test
        $this->entityManager->clear();
        $reloaded = $this->entityManager->find(ContentSource::class, $source->getId());
        $this->assertNotSame('unknown', $reloaded->getHealthStatus());
        $this->assertNotSame('testing', $reloaded->getHealthStatus()); // doit être terminé
    }
}
