<?php

namespace App\Tests\Feature\Scraping;

use ApiPlatform\Symfony\Bundle\Test\ApiTestCase;
use App\Domain\Scraping\Domain\Model\ScrapingJob;
use App\Domain\Scraping\Domain\Model\ScrapingStatus;
use App\Domain\Scraping\Domain\Model\ValueObject\ImageUrl;
use App\Domain\Scraping\Domain\Model\ValueObject\PageNumber;
use Ramsey\Uuid\Uuid;
use Symfony\Component\Messenger\MessageBusInterface;
use App\Domain\Shared\Domain\Contract\JobRepositoryInterface;
use App\Domain\Shared\Domain\Model\JobStatus;

class ScrapingStatusTest extends ApiTestCase
{
    private MessageBusInterface $messageBus;
    private JobRepositoryInterface $repository;

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

        self::bootKernel();

        $this->messageBus = self::getContainer()->get(MessageBusInterface::class);
        $this->repository = self::getContainer()->get(JobRepositoryInterface::class);
    }

    public function testGetScrapingStatus(): void
    {
        // Given
        $jobId = Uuid::uuid4()->toString();
        $job = new ScrapingJob($jobId, 'manga-123', 1, 'source-789');

        $job->start();

        $this->repository->save($job);

        // When
        $response = static::createClient()->request('GET', '/api/jobs?status=in_progress');

        // Then
        $this->assertResponseIsSuccessful();

        $responseData = $response->toArray();

        $this->assertArrayHasKey('hydra:member', $responseData);
        $this->assertIsArray($responseData['hydra:member']);
        $this->assertCount(1, $responseData['hydra:member']);

        $jobData = $responseData['hydra:member'][0];
        $this->assertEquals('/api/jobs/' . $jobId, $jobData['@id']);
        $this->assertEquals('Job', $jobData['@type']);
        $this->assertEquals($jobId, $jobData['id']);
        $this->assertEquals('scraping_job', $jobData['type']);
        $this->assertEquals(JobStatus::IN_PROGRESS->value, $jobData['status']);
        $this->assertEquals([
            'mangaId' => 'manga-123',
            'chapterNumber' => 1,
            'sourceId' => 'source-789'
        ], $jobData['context']);
    }

    public function testGetScrapingStatusForNonExistentJob(): void
    {
        // When
        $response = static::createClient()->request('GET', '/api/jobs/non-existent-id?status=in_progress', [
            'headers' => ['Accept' => 'application/json']
        ]);

        // Then
        $this->assertResponseStatusCodeSame(404);
    }

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

        self::ensureKernelShutdown();
    }
}
