<?php

declare(strict_types=1);

namespace App\Tests\Domain\Reader\Application\QueryHandler;

use App\Domain\Reader\Application\Query\GetChapterPage;
use App\Domain\Reader\Application\QueryHandler\GetChapterPageHandler;
use App\Domain\Reader\Domain\Exception\ChapterNotFoundException;
use App\Domain\Reader\Domain\Exception\PageNotFoundException;
use App\Domain\Reader\Domain\Model\ChapterContext;
use App\Domain\Reader\Domain\Model\Page;
use App\Domain\Reader\Domain\ValueObject\ChapterId;
use App\Domain\Reader\Domain\ValueObject\PageNumber;
use App\Tests\Domain\Reader\Adapter\InMemoryChapterRepository;
use PHPUnit\Framework\TestCase;

final class GetChapterPageHandlerTest extends TestCase
{
    private InMemoryChapterRepository $repository;
    private GetChapterPageHandler $handler;

    protected function setUp(): void
    {
        $this->repository = new InMemoryChapterRepository();
        $this->handler = new GetChapterPageHandler($this->repository);

        // Préparation des données de test
        $chapterId = new ChapterId('chapter-1');
        $context = new ChapterContext(
            $chapterId,
            null,
            null,
            'Test Manga',
            1.0,
            'Chapter 1',
            'path/to/cbz',
            1,
            10,
            true,
            new \DateTimeImmutable()
        );

        $pages = [];
        for ($i = 1; $i <= 10; $i++) {
            $pages[] = new Page(
                sprintf('page-%d', $i),
                new PageNumber($i),
                sprintf('/api/chapters/chapter-1/pages/%d', $i),
                800,
                600
            );
        }

        $this->repository->addChapter($chapterId, $context, $pages);
    }

    public function testItThrowsExceptionWhenChapterDoesNotExist(): void
    {
        $this->expectException(ChapterNotFoundException::class);
        $this->handler->handle(new GetChapterPage('invalid-id', 1));
    }

    public function testItThrowsExceptionWhenPageNumberExceedsTotalPages(): void
    {
        $this->expectException(PageNotFoundException::class);
        $this->handler->handle(new GetChapterPage('chapter-1', 11));
    }

    public function testItReturnsPageContentSuccessfully(): void
    {
        $response = $this->handler->handle(new GetChapterPage('chapter-1', 5));

        $this->assertEquals('page-5', $response->getId());
        $this->assertEquals(5, $response->getPageNumber());
        $this->assertNotEmpty($response->getBase64Content());
        $this->assertEquals('image/jpeg', $response->getMimeType());
        $this->assertEquals(['width' => 800, 'height' => 600], $response->getDimensions());
    }
} 