<?php

declare(strict_types=1);

namespace App\Domain\Reader\Application\QueryHandler;

use App\Domain\Reader\Application\Query\GetChapterPage;
use App\Domain\Reader\Application\Response\ChapterPageResponse;
use App\Domain\Reader\Domain\Contract\Repository\ChapterRepositoryInterface;
use App\Domain\Reader\Domain\Exception\ChapterNotFoundException;
use App\Domain\Reader\Domain\Exception\PageNotFoundException;
use App\Domain\Reader\Domain\ValueObject\ChapterId;
use App\Domain\Reader\Domain\ValueObject\PageNumber;

final readonly class GetChapterPageHandler
{
    public function __construct(
        private ChapterRepositoryInterface $chapterRepository
    ) {
    }

    public function handle(GetChapterPage $query): ChapterPageResponse
    {
        $chapterId = new ChapterId($query->getChapterId());
        $pageNumber = new PageNumber($query->getPageNumber());

        $totalPages = $this->chapterRepository->getTotalPagesForChapter($chapterId);

        if ($totalPages === 0) {
            throw ChapterNotFoundException::forChapter($chapterId);
        }

        if ($pageNumber->getValue() > $totalPages) {
            throw PageNotFoundException::forPage($chapterId, $pageNumber);
        }

        $page = $this->chapterRepository->getPageContent($chapterId, $pageNumber);

        return new ChapterPageResponse(
            $page->getId(),
            $page->getPageNumber()->getValue(),
            $page->getBase64Content(),
            $page->getMimeType(),
            $page->getDimensions()
        );
    }
} 