<?php

declare(strict_types=1);

namespace App\Domain\Reader\Application\QueryHandler;

use App\Domain\Reader\Application\Query\GetChapterPages;
use App\Domain\Reader\Application\Response\ChapterPagesResponse;
use App\Domain\Reader\Domain\Contract\Repository\ChapterRepositoryInterface;
use App\Domain\Reader\Domain\Exception\ChapterNotFoundException;
use App\Domain\Reader\Domain\ValueObject\ChapterId;

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

    public function handle(GetChapterPages $query): ChapterPagesResponse
    {
        $chapterId = new ChapterId($query->getChapterId());

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

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

        $pages = $this->chapterRepository->getPagesForChapter(
            $chapterId,
            $query->getPage(),
            $query->getItemsPerPage()
        );

        return new ChapterPagesResponse(
            $pages,
            $totalItems,
            $query->getPage(),
            $query->getItemsPerPage()
        );
    }
}
