<?php

namespace App\Domain\Manga\Application\QueryHandler;

use App\Domain\Manga\Application\Query\GetMangaChapters;
use App\Domain\Manga\Application\Response\ChapterListResponse;
use App\Domain\Manga\Application\Response\ChapterResponse;
use App\Domain\Manga\Domain\Contract\Repository\MangaRepositoryInterface;
use App\Domain\Manga\Domain\Exception\MangaNotFoundException;
use App\Domain\Manga\Domain\Model\Chapter;
readonly class GetMangaChaptersHandler
{
    public function __construct(
        private MangaRepositoryInterface $mangaRepository
    ) {}

    public function handle(GetMangaChapters $query): ChapterListResponse
    {
        $manga = $this->mangaRepository->findById($query->mangaId);
        if (!$manga) {
            throw new MangaNotFoundException();
        }

        $chapters = $this->mangaRepository->findChapters(
            mangaId: $query->mangaId,
            page: $query->page,
            limit: $query->limit,
            sortOrder: $query->sortOrder
        );

        $total = $this->mangaRepository->countChapters($query->mangaId);

        return new ChapterListResponse(
            chapters: array_map(
                fn (Chapter $chapter) => new ChapterResponse(
                    id: $chapter->getId(),
                    number: $chapter->getNumber(),
                    title: $chapter->getTitle(),
                    volume: $chapter->getVolume(),
                    isVisible: $chapter->isVisible(),
                    cbzPath: $chapter->getCbzPath(),
                    createdAt: $chapter->getCreatedAt()
                ),
                $chapters
            ),
            total: $total,
            page: $query->page,
            limit: $query->limit
        );
    }
}