<?php

namespace App\Tests\Domain\Manga\Adapter;

use App\Domain\Manga\Domain\Contract\Repository\ChapterRepositoryInterface;
use App\Domain\Manga\Domain\Model\Chapter;

class InMemoryChapterRepository implements ChapterRepositoryInterface
{
    /** @var array<string, Chapter> */
    private array $chapters = [];

    public function findById(string $id): ?Chapter
    {
        return $this->chapters[$id] ?? null;
    }

    public function findVisibleById(string $id): ?Chapter
    {
        $chapter = $this->chapters[$id] ?? null;
        if ($chapter && $chapter->isVisible()) {
            return $chapter;
        }

        return null;
    }

    public function findByMangaIdAndChapterNumber(string $mangaId, float $chapterNumber): ?Chapter
    {
        foreach ($this->chapters as $chapter) {
            if ($chapter->getMangaId() === $mangaId && $chapter->getNumber() === $chapterNumber) {
                return $chapter;
            }
        }

        return null;
    }

    public function save(Chapter $chapter): void
    {
        $this->chapters[$chapter->getId()] = $chapter;
    }

    public function delete(Chapter $chapter): void
    {
        unset($this->chapters[$chapter->getId()]);
    }

    public function findByMangaIdAndVolume(string $mangaId, int $volume): array
    {
        return array_filter(
            $this->chapters,
            fn (Chapter $chapter) => $chapter->getMangaId() === $mangaId && $chapter->getVolume() === $volume
        );
    }

    public function findVisibleByMangaIdAndVolume(string $mangaId, int $volume): array
    {
        return array_filter(
            $this->chapters,
            fn (Chapter $chapter) =>
                $chapter->getMangaId() === $mangaId &&
                $chapter->getVolume() === $volume &&
                $chapter->isVisible()
        );
    }

    public function findVisibleWithCbzByMangaIdAndVolume(string $mangaId, int $volume): array
    {
        return array_filter(
            $this->chapters,
            fn (Chapter $chapter) =>
                $chapter->getMangaId() === $mangaId &&
                $chapter->getVolume() === $volume &&
                $chapter->isVisible() &&
                $chapter->isAvailable()
        );
    }

    /**
     * Get all chapters
     */
    public function getAll(): array
    {
        return array_values($this->chapters);
    }

    /**
     * Clear all chapters
     */
    public function clear(): void
    {
        $this->chapters = [];
    }
}
